import { Component } from '@angular/core';
import { NavController, NavParams, ModalController } from 'ionic-angular';
import { HealthProvider } from '../../providers/health/health';
import { DetailPage } from '../detail/detail';
import { NewsReaderPage } from '../news-reader/news-reader';
import { InAppBrowser } from '@ionic-native/in-app-browser';


@Component({
    selector: 'page-home',
    templateUrl: 'home.html',
})
export class HomePage {
    products: Array<any>;
    posts: Array<any>;
    wpPosts: Array<any>;
    imageURL: string;
    postPage = 0;
    haveMore = true;
    constructor(public navCtrl: NavController, private healthProvider: HealthProvider, private vc: ModalController, private ab: InAppBrowser) {
        this.imageURL = this.healthProvider.imageURL;
        /*
    this.healthProvider.listNews()
      .subscribe(data => console.log(data));*/
        //hello 
        this.healthProvider.getPosts(this.postPage++)
            .subscribe( data => {
                this.posts = data.output;
            }, error => console.log("error ", JSON.stringify(error)) );
    }
    ionViewWillEnter() {
        console.log("view will enter");
        this.healthProvider.getWPPostCat(30)
            .subscribe( data => {
                console.log(data);
                this.wpPosts = data;
            } );
    }

    ionViewDidEnter() {
        /*
        this.healthProvider.getProducts()
            .subscribe(data => { 
                this.products = data.output;
                console.log("proudcts = ", this.products);
            }, 
                error => { console.log("error ", JSON.stringify(error));  } );
         */
    
    }
    openNavDetailsPage(item) {
        let modal = this.vc.create(DetailPage, {id: item});
        modal.present();
        //this.navCtrl.push(DetailPage, {  id: item });
    }
    openNewsReaderPage(item) {
        let modal = this.vc.create(NewsReaderPage, {id: item});
        modal.present();
        //this.navCtrl.push(DetailPage, {  id: item });
    }
    openLink(link: string) {
         this.ab.create(link, '_blank');
    }
	
	doInfinite(infiniteScroll) {
		console.log('Begin async operation');

		this.healthProvider.getPosts(this.postPage++)
            .subscribe( data => {
                console.log(data);
                if(data.output.length  !== 0  && data.output[0]._id.$oid == this.posts[this.posts.length - 1]._id.$oid)  {
                    infiniteScroll.enable(false);
                    this.haveMore = false;
                    return;	
                }
				this.posts = this.posts.concat(data.output);
				console.log("post ", this.posts);
				console.log('Async operation has ended');
				infiniteScroll.complete();
			}, error => console.log("error ", JSON.stringify(error)) );
	}

}
