import { Component } from '@angular/core';
import { ViewController, NavParams,  ToastController } from 'ionic-angular';
import { Events } from 'ionic-angular';

import * as pnut from 'pnut-butter';

@Component({
  template: `
<ion-list>
  <button ion-item (click)="browse()">Open in Browser</button>
  <button ion-item (click)="share()">Share</button>
  <button ion-item *ngIf="showDelBtn" (click)="delete()">Delete</button>
</ion-list>
`
})
export class PostMenu {

  showDelBtn: boolean = false;

  constructor(public navParams: NavParams, public viewCtrl: ViewController, public toastCtrl: ToastController,
    public events: Events) {
    if (navParams.data.me == navParams.data.post.user.username) {
      this.showDelBtn = true;
    } else {
      this.showDelBtn = false;
    }
  }

  browse() {
    window.open('https://posts.pnut.io/' + this.navParams.data.post.id, '_system');
    this.close();
  }

  share() {
    (<any>window).shareContentPlugin.share(this.navParams.data.post.content.text, function(e) {
      console.log('sharing post:');
      console.log(JSON.stringify(e));
    }, function(e) {
      console.log('sharing failed:');
      console.log(JSON.stringify(e));
    });
    this.close();
  }

  delete() {
    pnut.deletePost(this.navParams.data.post.id).then(res => {
      console.log(res);
      this.presentToast('Post Deleted');
      this.events.publish('stream:reload', {});
    }).catch( err => {
      console.log('-error-');
      console.log(err);
    });
    this.close()
  }

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

  close() {
    this.viewCtrl.dismiss();
  }
}
