import { Component } from "@angular/core";
import {
  IonicPage,
  NavController,
  MenuController,
  InfiniteScroll,
  Refresher,
  LoadingController
} from "ionic-angular";
import { Storage } from "@ionic/storage";
import { WriteTweetPage } from "../write-tweet/write-tweet";
import { FeedProvider } from "../../providers/feed/feed";

@IonicPage()
@Component({
  selector: "page-home",
  templateUrl: "home.html"
})
export class HomePage {
  menuController: MenuController;
  tweets;
  userId: string;

  constructor(
    public navCtrl: NavController,
    private menuCtrl: MenuController,
    private storage: Storage,
    private feed: FeedProvider,
    private loadingCtrl: LoadingController
  ) {
    this.storage.get("userId").then(userId => (this.userId = userId));
  }

  ionViewDidLoad() {
    this.menuCtrl.enable(true, "sideNav");
  }

  ionViewDidEnter() {
    const loading = this.loadingCtrl.create();
    loading.present();

    this.feed
      .loadHomeTimeline(this.userId)
      .then(tweets => (this.tweets = tweets))
      .catch(err => console.error(err))
      .then(() => loading.dismiss());
  }

  doRefresh(refresher: Refresher) {
    this.feed.loadHomeTimeline(this.userId).then(tweets => {
      this.tweets = tweets;
      refresher.complete();
    });
  }

  loadMore(infiniteScroll: InfiniteScroll) {
    this.feed
      .loadHomeTimeline(
        this.userId,
        this.oldestPublicTweet,
        this.oldestPrivateTweet
      )
      .then(tweets => {
        this.tweets = this.tweets.concat(tweets);
        infiniteScroll.complete();
      });
  }

  writeTweet() {
    this.navCtrl.push(WriteTweetPage);
  }

  get publicTweets() {
    return this.tweets.filter(tweet => !tweet.private_tweet);
  }

  get privateTweets() {
    return this.tweets.filter(tweet => tweet.private_tweet);
  }

  get oldestPublicTweet() {
    if (this.publicTweets.length > 0) {
      return this.publicTweets.reduce(
        (acc, cur) => (acc.id < cur.id ? acc : cur)
      );
    } else {
      return undefined;
    }
  }

  get oldestPrivateTweet() {
    if (this.privateTweets.length > 0) {
      return this.privateTweets.reduce(
        (acc, cur) =>
          new Date(acc.created_at) < new Date(cur.created_at) ? acc : cur
      );
    } else {
      return undefined;
    }
  }
}
