import { Component } from '@angular/core';
import { NavController, NavParams, ModalController, ToastController, PopoverController } from 'ionic-angular';
import { NewPostModal, PostMenu } from '../stream/stream';

import * as pnut from 'pnut-butter';

/**
 * Generated class for the ThreadPage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */
@Component({
  selector: 'page-thread',
  templateUrl: 'thread.html',
})
export class ThreadPage {

  title: string;
  posts: Array<Object> = [];
  myUsername: string;

  constructor(public navCtrl: NavController, public navParams: NavParams, public modalCtrl: ModalController,
    public popoverCtrl: PopoverController, public toastCtrl: ToastController) {
    this.posts = this.navParams.data.posts;
    this.myUsername = this.navParams.data.me;
  }

  showReplyPost(postData) {
    let newPostModal = this.modalCtrl.create(NewPostModal, {type: 'reply', post: postData});
    newPostModal.present();
  }

  showQuotedPost(postData) {
    console.log(postData);
    let newPostModal = this.modalCtrl.create(NewPostModal, {type: 'quote', post: postData});
    newPostModal.present();
  }

  bookmark(postid, bookmarked) {
    if (bookmarked) {
      pnut.deleteBookmark(postid).then(res => {
        console.log(res);
        this.updatePost(res.data.id);
        this.presentToast("Bookmark updated.");
      }).catch(err => {
        console.log(err);
      });
    } else {
      pnut.bookmark(postid).then(res => {
        console.log(res);
        this.updatePost(res.data.id);
        this.presentToast("Bookmark updated.");
      }).catch(err => {
        console.log(err);
      });
    }
  }

  repost(postid, reposted) {
    if (reposted) {
      pnut.deleteRepost(postid).then(res => {
        console.log(res);
        this.updatePost(res.data.id);
        this.presentToast("Repost updated.");
      }).catch(err => {
        console.log(err);
      });
    } else {
      pnut.repost(postid).then(res => {
        console.log(res);
        this.updatePost(res.data.id);
        this.presentToast("Repost updated.");
      }).catch(err => {
        console.log(err);
      });
    }
  }

  updatePost(postid) {
    pnut.post(postid, {include_raw: 1}).then(res => {
      for (var i = 0; i < this.posts.length; i++) {
        if (this.posts[i]['id'] === postid) {
          this.posts[i] = res.data;
          break;
        }
      }
    }).catch(err => {
      console.log(err);
    });
  }

  presentPostMenu(myEvent, postData) {
    let popover = this.popoverCtrl.create(PostMenu, {post: postData, me: this.myUsername});
    popover.present({ev: myEvent});
  }

  presentToast(text) {
    let toast = this.toastCtrl.create({
      position: 'top',
      message: text,
      duration: 2000
    });
    toast.present();
  }

}
