import { Component } from '@angular/core';
import { ViewController, NavParams,  ToastController } from 'ionic-angular';
import { Events } from 'ionic-angular';
import { Device } from '@ionic-native/device';
import { ClipboardService } from 'ngx-clipboard';

import * as pnut from 'pnut-butter';

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

  showDelBtn: boolean = false;
  showShareBtn: boolean = false;
  postURL: string;

  constructor(public navParams: NavParams, public viewCtrl: ViewController, public toastCtrl: ToastController,
    public events: Events, private clipboardSrv: ClipboardService, private device: Device) {
    this.postURL = 'https://posts.pnut.io/' + this.navParams.data.post.id;
    if (navParams.data.me == navParams.data.post.user.username) {
      this.showDelBtn = true;
    } else {
      this.showDelBtn = false;
    }
    if (this.device.platform === "Android" || this.device.platform === "amazon-fireos") {
      this.showShareBtn = true;
    }
  }

  browse() {
    window.open(this.postURL, '_system');
    this.close();
  }

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

  copy() {
    this.clipboardSrv.copyFromContent(this.parsePost());
    this.presentToast('Post copied');
    this.close();
  }

  parsePost() {
    let text = this.navParams.data.post.content.text;
    let links = this.navParams.data.post.content.entities.links;
    if (links.length > 0) {
      for (var i = 0; i < links.length; i++) {
        text += "\n";
        if (typeof links[i].title !== "undefined") {
          text += links[i].title + " - ";
        }
        text += links[i].link;
      }
    }
    return text;
  }

  copyPostURL() {
    this.clipboardSrv.copyFromContent(this.postURL);
    this.presentToast('Post link copied');
    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();
  }
}
