import { Component } from '@angular/core';
import { NavController, NavParams, ActionSheetController, ToastController, AlertController } from 'ionic-angular';
import { CustomerListPage } from "../customer-list/customer-list";
import { Partner } from "../../models/partner";
import { DataProvider } from "../../providers/data-provider";
import { PhoneProvider } from "../../providers/phone-provider";

@Component({
    selector: 'page-customer-details',
    templateUrl: 'customer-details.html',
    providers: [ Partner, PhoneProvider ]
})
export class CustomerDetailsPage {

    constructor(
        public navCtrl: NavController,
        public navParams: NavParams,
        public actionSheetCtrl: ActionSheetController,
        public toastCtrl: ToastController,
        public alertCtrl: AlertController,
        public phone: PhoneProvider,
        public customer: Partner,
        public db: DataProvider
    ) { 
        if (!(this.navParams.data instanceof CustomerListPage)) {
            this.customer = this.navParams.data;
            this.customer.doc_state = "updated";
        }
    }

    /**
     *
     */
    ionViewDidLoad() {
        this.phone.enableShakeWatcher().subscribe(() => this.askIfGetCurrentPosition(), e => console.log(e));
    }

    /**
     *
     */
    ionViewDidLeave() {
        this.phone.disableShakeWatcher();
    }

    /**
     *
     */
    private askIfGetCurrentPosition(): void {
        this.alertCtrl.create({
            title: "Confirmar",
            message: "Desea obtener la posición por GPS?",
            buttons: [
                {
                    text: "Cancelar",
                    handler: () => console.log("Canceled")
                },
                {
                    text: "Aceptar",
                    handler: () => this.checkGpsStatus()
                }
            ]
        }).present();
    }

    /**
     *
     */
    private checkGpsStatus(): void {
        this.phone.getGpsStatus().subscribe(status => { 
            if (status) {
                this.getCurrentPosition();

            } else {
                this.alertCtrl.create({
                    title: "Confirmar",
                    message: "El GPS se encuentra desactivado, desea activarlo?",
                    buttons: [
                        {
                            text: "Cancelar",
                            handler: () => console.log("Canceled")
                        },
                        {
                            text: "Aceptar",
                            handler: () => this.phone.switchToGpsSettings()
                        }
                    ]
                }).present();
            }
        });
    }

    /**
     *
     */
    private getCurrentPosition(): void {
        this.phone.getCurrentPosition().subscribe(position => { 
            this.customer.partner_latitude = position.coords.latitude;
            this.customer.partner_longitude = position.coords.longitude;

            this.toastCtrl.create({
                message: "Posición GPS obtenida",
                duration: 3000
            }).present();
        }, e => { 
            console.log(e);
            
            this.toastCtrl.create({
                message: "No se ha podido obtener la posición",
                duration: 3000
            }).present();
        });
    }

    /**
     *
     */
    private isValidForm(): boolean {
        if (this.customer.name) {
            return true;
        }

        return false;
    }

    /**
     *
     */
    showPhotoOptions(): void {
        this.actionSheetCtrl.create({
            title: "Tomar una foto",
            buttons: [
                {
                    text: "Desde la cámara",
                    icon: "camera",
                    handler: () => {
                        this.takePicture("camera");
                    }
                },
                {
                    text: "Desde la galería",
                    icon: "images",
                    handler: () => {
                        this.takePicture("album");
                    }
                },
                {
                    text: "Cancelar",
                    role: "cancel"
                }
            ]
        }).present();
    }

    /**
     *
     */
    private takePicture(source: string): void {
        this.phone.openCamera(source).subscribe(image => { 
            this.customer.image_medium = image;
            this.customer.image_small = image;
        }, e => { 
            console.log(e);
            
            this.toastCtrl.create({
                message: "No se ha podido tomar la foto",
                duration: 3000
            }).present();
        });
    }

    /**
     *
     */
    save(): void {
        if (!this.isValidForm()) {
            return;
        }

        this.customer.customer = true;

        this.db.save(DataProvider.DOCS.PARTNER, this.customer).then(c => { 
            if (this.navParams.data instanceof CustomerListPage) {
                this.navParams.data.add(c);
            }

            this.navCtrl.pop(this);
        }).catch(e => { 
            console.log(e);
            
            this.toastCtrl.create({
                message: "No se ha podido guardar los datos",
                duration: 3000
            }).present();
        });
    }
}
