import { Component, OnInit} from '@angular/core';
import { MenuController } from 'ionic-angular';
import Stomp from 'stompjs';
import SockJS from 'sockjs-client';

import { NavController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage implements OnInit{

  constructor(public navCtrl: NavController, public menu: MenuController) {
    this.menu.enable(true);
  }

  private stompClient ;
  posts = [];
  userId = 1;
  userPostUrl = "/app/posts";
  postInput = "";

  ngOnInit() {
    this.connect();  
  }
  connect() {
    const socket = new SockJS('https://fast-headland-39537.herokuapp.com/vault-socket');
    this.stompClient = Stomp.over(socket);

    this.stompClient.connect({}, (frame) => {
      console.log('Connected: ' + frame);
      this.stompClient.subscribe('/topic/posts', (post) => {
        this.posts.unshift(JSON.parse(post.body));
     });
    });
  }

  sendPost() {
    this.stompClient.send(this.userPostUrl, {}, JSON.stringify({'id': '','message': this.postInput, 'userId': this.userId}))
    this.postInput = "";
  }



}
