import { Component, ViewChild, ChangeDetectorRef } from '@angular/core';
import { NavController, NavParams, ModalController, Content } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { Events } from 'ionic-angular';
import { LoginPage } from '../login/login';
import { NewPostModal } from '../stream/new-post';

import * as pnut from 'pnut-butter';

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

  @ViewChild(Content) content: Content;

  title: string;
  posts: Array<Object> = [];
  since_id: string;
  before_id: string;
  fetcher: any;
  fcaller: any;
  myUsername: string;
  showScrollBtn: boolean = false;
  showUnified: boolean;
  ccOnReply: boolean = false;
  hideImg: boolean = false;

  constructor(public navCtrl: NavController, public navParams: NavParams,
    public modalCtrl: ModalController, private storage: Storage,
    private changeDetectorRef: ChangeDetectorRef, public events: Events) {

    this.storage.get('cc').then((val) => {
      this.ccOnReply = val;
    });

    this.storage.get('hideimg').then((val) => {
      this.hideImg = val;
    });

    this.storage.get('unified').then((val) => {
      this.showUnified = val;

      switch (navParams.data.stream) {
        case 'global':
          this.title = 'Global';
          this.fetcher = pnut.global;
          this.fetchPosts();
          break;
        case 'personal':
          this.title = 'Timeline';
          console.log(this.showUnified);
          this.fetcher = this.showUnified ? pnut.unified : pnut.personal;
          this.fetchPosts();
          break;
        case 'mentions':
          this.title = 'Mentions';
          this.fetcher = pnut.mentions;
          this.fetchMyPosts();
          break;
        case 'bookmarks':
          this.title = 'Bookmarks';
          this.fetcher = pnut.bookmarks;
          this.fetchMyPosts();
          break;
      }

    }).catch(err => {
      console.log('ERROR: ' + err);
    });


    pnut.user('me').then(res => {
      this.myUsername = res.data.username;
    }).catch(err => {
      // console.log('-*-');
      // console.log(JSON.stringify(err));
    });

    this.events.subscribe('stream:reload', (event) => {
      console.log('-reload-');
      this.refreshPage();
    });

  }

  ngAfterViewInit() {
    this.content.ionScroll.subscribe((event) => {
      // console.log('scrolling ', event);
      if (event.scrollTop > 0) {
        this.showScrollBtn = true;
      } else {
        this.showScrollBtn = false;
      }
      this.changeDetectorRef.detectChanges();
    });
  }

  refreshPage() {
    // this.navCtrl.setRoot(this.navCtrl.getActive().component);
    this.navCtrl.setRoot(StreamPage, {stream: 'personal'});
  }

  fetchOlderPosts(infiniteScroll) {
    let params = {
      include_deleted: 0,
      include_raw: 1,
      include_reposted_by:1,
      before_id: this.before_id,
      count: 40
    };
    if (this.title === 'Mentions') {
      this.fcaller = this.fetcher('me', params);
    } else {
      this.fcaller = this.fetcher(params);
    }
    this.fcaller.then(res => {
      if (res.data.length > 0) {
        this.posts.push.apply(this.posts, this.parseData(res.data));
        this.before_id = res.meta.min_id;
      }
      console.log('since_id: ' + this.since_id);
      console.log('before_id: ' + this.before_id);
      infiniteScroll.complete();
    }).catch(err => {
      console.log(err);
    });
  }

  fetchNewerPosts(refresher) {
    let params = {
      include_deleted: 0,
      include_raw: 1,
      include_reposted_by: 1,
      since_id: this.since_id,
      count: 40
    };
    if (this.title === 'Mentions') {
      this.fcaller = this.fetcher('me', params);
    } else {
      this.fcaller = this.fetcher(params);
    }
    this.fcaller.then(res => {
      if (res.data.length > 0) {
        Array.prototype.unshift.apply(this.posts, this.parseData(res.data));
        this.since_id = res.meta.max_id;
      }
      console.log('since_id: ' + this.since_id);
      console.log('before_id: ' + this.before_id);
      refresher.complete();
    }).catch(err => {
      console.log(err);
    });
  }

  fetchPosts() {
    let params = {
      include_deleted: 0,
      include_raw: 1,
      include_reposted_by: 1,
      count: 40
    };
    this.fetcher(params).then(res => {
      if (res.meta.code === 401) {
        this.storage.clear();
        this.navCtrl.setRoot(LoginPage);
      } else {
        this.posts = this.parseData(res.data);
        this.since_id = res.meta.max_id;
        this.before_id = res.meta.min_id;
        console.log('since_id: ' + this.since_id);
        console.log('before_id: ' + this.before_id);
      }

    });
  }

  parseData(data) {
    var pdata = [];
    for (var i = 0; i < data.length; i++) {
      if (!data[i].is_deleted) {
        if (data[i]['repost_of']) {
          data[i] = data[i]['repost_of']
          var reposted_by_string = "";
          for (var j = 0; j < data[i]['reposted_by'].length; j++) {
            reposted_by_string = reposted_by_string + data[i]['reposted_by'][j]['username'] + ", ";
          }
          // data[i]['reposted_by_string'] = "Reposted by: " + reposted_by_string;
        }
        if (data[i].content) {
          for (var k = 0; k < data[i]['content']['entities']['mentions'].length; k++) {
            var men = data[i]['content']['entities']['mentions'][k]['text'];
            if (this.myUsername === men) {
              data[i]['you_are_mentioned'] = true;
            }
          }
        }
        pdata.push(data[i]);
      }
    }
    return pdata;
  }

  fetchMyPosts() {
    console.log('-- fetching mentions --');
    this.fetcher('me', {include_raw: 1, count: 40}).then(res => {
      if (res.meta.code === 401) {
        this.storage.clear();
        this.navCtrl.setRoot(LoginPage);
      } else {
        this.posts = res.data;
        this.since_id = res.meta.max_id;
        this.before_id = res.meta.min_id;
        console.log('since_id: ' + this.since_id);
        console.log('before_id: ' + this.before_id);
      }
    });
  }

  showNewPost() {
    let newPostModal = this.modalCtrl.create(NewPostModal, {me: this.myUsername});
    newPostModal.present();
  }

  scrollToTop() {
    this.content.scrollToTop();
  }

}
