import { Component } from '@angular/core';
import { ViewController, NavParams, ToastController, Events } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { FileChooser } from '@ionic-native/file-chooser';
import { FilePath } from '@ionic-native/file-path';
import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer';

import * as pnut from 'pnut-butter';

@Component({
  selector: 'modal-newpost',
  templateUrl: 'new-post.html',
})
export class NewPostModal {
  title: string;
  replyid: string;
  ptext: string = "";
  showProgress: boolean = false;
  files: Array<Object> = [];
  fname: string = "";
  fpath: string = "";
  options: Object = {};
  myUsername: string;
  authToken: string;
  longpost: Object = {};
  raw: {type: string, value: Object}[] = [];

  constructor(public navParams: NavParams, public viewCtrl: ViewController, public toastCtrl: ToastController,
    private fileChooser: FileChooser, private storage: Storage, public events: Events, private filePath: FilePath,
    private transfer: FileTransfer) {
    console.log(JSON.stringify(this.navParams));
    this.myUsername = navParams.data.me;
    if (navParams.data.type === 'reply') {
      this.replyid = navParams.data.post.id;
      this.options = {replyTo: this.replyid};
      if (navParams.data.post.user.username !== this.myUsername) {
        this.ptext = "@" + navParams.data.post.user.username + " ";
      } else {
        this.ptext = ""
      }
      if (navParams.data.post.content.entities) {
        if (navParams.data.post.content.entities.mentions.length > 0) {
          this.ptext = this.ptext + this.parseMentions(navParams.data.post.content.entities.mentions);
        }
      }
      this.title = "Reply to " + navParams.data.post.user.username
    } else if (navParams.data.type === 'quote') {
      this.ptext = " >> @" + navParams.data.post.user.username + ": " + navParams.data.post.content.text;
      this.title = "New Post";
    } else {
      this.title = "New Post";
    }
    this.storage.get('token').then((val) => {
      this.authToken = val;
    });
  }

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

  send() {

    if (this.ptext.length > 254) {
      this.longpost = {
        'title': '',
        'body': this.ptext,
        'tstamp': new Date().valueOf()
      }
      this.ptext = this.ptext.substr(0, 40) + "... - http://chimpnut.nl/u/";
      this.ptext = this.ptext + this.navParams.data.me + "/lp/{object_id} - #longpost";
      this.raw.push({
        type: "nl.chimpnut.blog.post",
        value: this.longpost
      });
    }

    this.options['raw'] = this.raw;
    pnut.createPost(this.ptext, this.options).then(res => {
      console.log('-success-');
      console.log(JSON.stringify(res));
      this.presentToast("Status posted.");
      this.events.publish('stream:reload', {});
    }).catch(err => {
      console.log('-error posting-');
      console.log(JSON.stringify(err));
    });
    this.viewCtrl.dismiss();
  }

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

  parseMentions(mentions) {
    let mtext = ""
    for(var i = 0; i < mentions.length; i++) {
      let mu = mentions[i].text;
      if (mu !== this.myUsername) {
        mtext += "@" + mu + " ";
      }
    }
    if (mtext.length > 0) {
      if (this.navParams.data.cc) {
        mtext = "\n/" + mtext;
      }
      return mtext;
    } else {
      return "";
    }
  }

  textCount() {
    let counttext = ""
    let count = 254 - this.ptext.length
    if (count < 1) {
      counttext = "longpost"
    } else {
      counttext = String(count)
    }
    return counttext
  }

  attachImage() {
    // console.log('file chooser');
    const fileTransfer: FileTransferObject = this.transfer.create();

    this.fileChooser.open().then(uri => {
      console.log('File URI: ' + uri);
      this.filePath.resolveNativePath(uri).then(filePath => {
        this.fpath = filePath;
        this.fname = filePath.split('/').pop();

        let options: FileUploadOptions = {
          fileKey: 'content',
          fileName: this.fname,
          params: {
            name: this.fname,
            type: 'com.monkeystew.goober_m',
            is_public: true
          },
          headers: {'Authorization': 'Bearer ' + this.authToken}
        }

        this.showProgress = true;
        fileTransfer.upload(this.fpath, 'https://api.pnut.io/v0/files', options).then((response) => {

          let rdata = JSON.parse(response.response);
          let oembed = {
            '+io.pnut.core.file': {
              file_id: rdata.data.id,
              file_token: rdata.data.file_token,
              format: 'oembed'
            }
          }
          // console.log(JSON.stringify(oembed));
          this.raw.push({
            type: "io.pnut.core.oembed",
            value: oembed
          });
          this.files.push({
            name: this.fname,
            link: rdata.data.link,
            id: this.raw.length - 1
          });
          this.showProgress = false;
        }).catch((err) => { // fileTransfer

          this.showProgress = false;
          let edata = JSON.parse(err.body);
          this.presentToast(edata.meta.error_message);
        });

      }).catch(err => {  // filePath
        console.log('-error getting filepath-');
        console.log(err);
      });

    }).catch(err => { // fileChooser
      console.log(err);
    });

  }

  unattach(id) {
    console.log('removing item ' + id);
    this.raw.splice(id, 1);
    this.files.splice(id, 1);
  }
}
