import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { ProfilePage } from '../../pages/profile/profile';

import * as pnut from 'pnut-butter';

/**
 * Generated class for the UserListPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@Component({
  selector: 'page-user-list',
  templateUrl: 'user-list.html',
})
export class UserListPage {

  private list: string;
  private userid: string;
  private users: Array<Object> = [];
  private myUsername: string;
  private before_id: string;
  private fetcher: any;

  constructor(public navCtrl: NavController, public navParams: NavParams) {
    this.list = this.navParams.data.list;
    this.userid = this.navParams.data.userid;
    this.myUsername = this.navParams.data.username;
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad UserListPage');
    let params = {
      include_deleted: 0,
      include_raw: 1,
      count: 40
    };
    if (this.list == "Followers") {
      this.fetcher = pnut.followers;
    } else if (this.list == "Following") {
      this.fetcher = pnut.following;
    }
    this.fetcher(this.userid, params).then(res => {
      this.users = res.data;
      this.before_id = res.meta.min_id;
    });
  }

  showProfile(user) {
    this.navCtrl.push(ProfilePage, {user: user, me: this.myUsername});
  }

  fetchMoreUsers(infiniteScroll) {
    let params = {
      include_deleted: 0,
      include_raw: 1,
      before_id: this.before_id,
      count: 40
    };
    this.fetcher(this.userid, params).then(res => {
      if (res.data.length > 0) {
        this.users.push.apply(this.users, res.data);
        this.before_id = res.meta.min_id;
      }
      infiniteScroll.complete();
    });
  }

}
