import { Component } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { IonicPage, NavController, NavParams, ViewController, AlertController } from 'ionic-angular';
import { HealthProvider } from '../../providers/health/health';

import { NativeStorage } from '@ionic-native/native-storage';
/**
 * Generated class for the DetailPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
    selector: 'page-detail',
    templateUrl: 'detail.html',
})
export class DetailPage {
    id: string;
    info: string = "info";
    product;
    actId;
    token;
    qr;
    linkRec;

    constructor(public navCtrl: NavController, public navParams: NavParams, private hp: HealthProvider, private nativeStorage: NativeStorage, private vc: ViewController, private alertCtrl: AlertController, private sanitizer: DomSanitizer) {

        console.log(navParams);
        this.id = navParams.data.id;
        console.log(this.id);
        this.hp.getProduct(this.id)
            .subscribe(data => {
                this.product = data.output;	
                console.log(this.product);
            });

        this.nativeStorage.getItem('token')
            .then(
                data => { 
                    this.token = data;
                },
                error => {
                    console.log("Error to get token");
                });
    }
    onActChange(newValue) {
        console.log(this.actId);
    }
    cutPoint() {
        this.hp.cutPoint(this.token, this.id)
            .subscribe( data => {
                console.log(data);
                //this.qr = this.hp.qrURL + data.output.qr;
                this.linkRec = this.sanitizer.bypassSecurityTrustUrl(this.product.link);
                let alert = this.alertCtrl.create({
                    title: "ผลการทำรายการ",
                    message: `ขณะนี้ระบบทำการตัด ${this.product.cal_return } คะแนนจาก wallet คุณเรียบร้อยแล้ว โปรดตรวจสอบคูปองได้ที่ My Profile -> History`,
                    buttons: ['OK']
                });
                alert.present();
            }, error => {
                console.log(JSON.stringify(error));
                let alert = this.alertCtrl.create({
                    title: "ผลการทำรายการ",
                    message: error.error,
                    buttons: ['OK']
                });
                alert.present();
            } );
    }

    ionViewDidLoad() {
        console.log('ionViewDidLoad DetailPage');
    }

    dismiss() {
        this.vc.dismiss();
    }

}
