import { Component, ViewChild } from '@angular/core';
import { NavController, AlertController, Content
    , LoadingController, ModalController} from 'ionic-angular';
import { InAppBrowser } from '@ionic-native/in-app-browser';

import { NativeStorage } from '@ionic-native/native-storage';
import { HealthProvider } from '../../providers/health/health';
import { CouponViewPage } from '../coupon-view/coupon-view';
import { HTTP  } from '@ionic-native/http';
import { UserAgent } from '@ionic-native/user-agent';


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

//@IonicPage()
@Component({
    selector: 'page-login',
    templateUrl: 'login.html',
})
export class LoginPage {
    browser;
    token;
    isLogin = false;
    seg = "myinfo"
    profileObject;
    acts;
    hists;
    sexMap = {'M': 'Male', 'F': 'Female'};
    points = 0;
    imageURL: string;
    haveSelectAct =  false;
    haveSelectHistory =  false;

    @ViewChild(Content) content: Content;

    refreshText = "Refresh";

    constructor(public navCtrl: NavController, private iab: InAppBrowser, 
        private nativeStorage: NativeStorage,
        private hp: HealthProvider, 
        private alertCtrl: AlertController,
        private http: HTTP, private lc: LoadingController,
        private vc: ModalController,
        private userAgent: UserAgent
    ) {
        this.userAgent.get()
            .then((res: any) => console.log(res))
            .catch((error: any) => console.error(error));
		    this.imageURL = this.hp.imageURL;	
    }
    ionViewDidLoad() {
        //ionViewDidLoad() {
        console.log("will enter");
        this.nativeStorage.getItem('token')
            .then(
                data => { 
                    console.log('token == ', data);
                    this.token = data;
                    
                    this.hp.getMyDetail(this.token)
                        .subscribe(
                            acts => { 
                                console.dir(acts.output.firstname, acts.output.lastname);
                                this.nativeStorage.setItem('profileObject', acts.output);
                                this.profileObject = acts.output;
                                this.isLogin = true;

                            },
                            error => {
                                console.error("error ", error.error);
                                this.isLogin = false;
                            });
                    this.hp.getHistory(this.token)
                        .subscribe(
                            hists => {
                                console.log(JSON.stringify(hists.output));
                                this.hists = hists.output;
                                this.content.resize();
                            },
                            error => {
                                console.error("hists ", error.error);
                            }
                        );

                },
                error => {
                    this.isLogin = false;
                }
            );
    }

    selectWallet() {
        this.hp.getPoint(this.token)
            .subscribe( data => {
                if( data.output != null  )
                    this.points = data.output.points;
                this.content.resize();
            });
    }
    refreshSwitch(refresher) {
        if( this.seg == "activities" ) {
            this.hp.myActivities(this.token)
                .subscribe(
                    acts => { 
                        this.acts  = acts.output;
                        refresher.complete();
                        this.content.resize();
                    },
                    error => {
                        console.error("error in acts", error);
                        this.isLogin = false;
                    });

        }else if(this.seg == "myWallet"){
            this.hp.getPoint(this.token)
                .subscribe( data => {
                    if( data.output != null  )
                        this.points = data.output.points;
                    refresher.complete();
                    //this.content.resize();
                });
        }
        else if(this.seg == "history") {
            this.hp.getHistory(this.token)
                .subscribe(
                    hists => {
                        this.hists = hists.output;
                        this.content.resize();
                        refresher.complete();
                    },
                    error => {
                        console.error("hists ", error);
                    }
                );
        }else {
            refresher.complete();
            console.log("seg ", this.seg);
        }   
    }
    getMyActivities(fromRefresher = false) {
        if( this.haveSelectAct == true )
            return;

        const loader = this.lc.create({
                  content: "Loading Activities",
                
        });
        loader.present();
        this.hp.myActivities(this.token)
            .subscribe(
                acts => { 
                    this.haveSelectAct = true;
                    this.acts  = acts.output;
                    loader.dismiss();
                    this.content.resize();
                    this.isLogin = true;
                },
                error => {
                    console.error("error in acts", error);
                    this.isLogin = false;
                });
    }
    /*
  ionViewDidLoad() {
    console.log('ionViewDidLoad LoginPage');
  }*/
    redeem(act, si) {
        this.hp.redeem(this.token, act)
            .subscribe( data => {
                act.used = true;
                si.close();
                /*
        let index =  this.acts.indexOf(act, 0);
        if( index > -1 ) {
          this.acts.splice(index,1);
        }*/
                //this.getMyActivities();
                let alert = this.alertCtrl.create({
                    title: 'You Points !!',
                    message: 'Your Have '+data.output.point+' points for the activity<br>Activity Detail<br>Distance = '+data.output.detail.distance+'<br>Callories = '+data.output.detail.calories + " kcal<br>Activity type = "+data.output.detail.type ,
                    buttons: ['Ok']
                });
                alert.present()
                //console.log("data ", data);
            });
        //update act
    }
    public loadStartEventHandler(event) {

            console.log("url", event.url);
            //browser.insertCSS({ code: "body{color: red;" });
            if ((event.url).indexOf('?tk=') !== -1) {
                let token = event.url.slice(event.url.indexOf('?tk=') + '?tk='.length);
                token = token.replace("#_=_", "");
                // here is your token, now you can close the InAppBrowser
                console.log("token", token);
                this.token = token;
                this.nativeStorage.setItem('token', this.token)
                    .then(
                        () => { 
                            console.log('Stored item!');
                            this.nativeStorage.getItem('token')
                                .then(
                                    data => { 
                                        this.navCtrl.setRoot(this.navCtrl.getActive().component);


                                        //this.navCtrl.parent.select(4);
                                        console.log(data);
                                    },
                                    error => console.error(error)
                                );
                        },
                        error => console.error('Error storing item', error)
                    );
                this.browser.close();
            }
    }
    openWeb() {
        console.log("open browser");
        //this.browser = this.iab.create('http://localhost:8000/strava/', '_blank');
        this.browser = this.iab.create('https://www.strava.com/oauth/authorize?client_id=21430&redirect_uri=https%3A%2F%2Fhc.simplico.net%2Fstrava%2Fauthorized&approval_prompt=auto&response_type=code&scope=activity:read_all,profile:read_all', '_blank', "clearsessioncache=yes");
        this.browser.on('loadstart').subscribe(event => {
            this.loadStartEventHandler(event);
        });
        this.browser.on('loadstop').subscribe(event => {
            console.log(event);
        });
    }

    doRefresh(refresher) {
        console.log("Event ", refresher);
        this.refreshText = "Please Wait ...";
        this.hp.getPoint(this.token)
            .subscribe( data => {

                this.refreshText = "Refresh Complete";
                setTimeout(() => this.refreshText = "Refresh" , 2000);
                console.log(data);
                if( data.output != null )
                    this.points = data.output.points;
                this.content.resize();
            });
    }
    deleteAllCookies() {
        var cookies = document.cookie.split(";");

        for (var i = 0; i < cookies.length; i++) {
            var cookie = cookies[i];
            var eqPos = cookie.indexOf("=");
            var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
            document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";

        }

    }
    logout() {
        this.http.clearCookies();
        //window.cookies.clear(function() {});
        //this.deleteAllCookies();
        this.nativeStorage.clear()
            .then(() => {
                console.log("remove");
                this.isLogin = false;
                this.token = "";
                console.log(this.token);
                this.navCtrl.parent.select(0);
            });
    }

    openViewCoupon(item) {
        let modal = this.vc.create(CouponViewPage, {item: item});
        modal.present();
    }

}
