import { Component } from '@angular/core';
import { NavController, LoadingController, ToastController, PopoverController, AlertController } from 'ionic-angular'
import { CallNumber } from "ionic-native";
import { DefaultListable } from "../../defaults/default-listable";
import { INavigable } from "../../interfaces/navigable-interface";
import { Partner } from "../../models/partner";
import { DataProvider } from "../../providers/data-provider";
import { CustomerDetailsPage } from "../customer-details/customer-details";
import { CustomerOptions } from "./customer-options";
import { PhoneProvider } from "../../providers/phone-provider";

@Component({
    selector: 'page-customer-list',
    templateUrl: 'customer-list.html',
    providers: [ PhoneProvider ]
})
export class CustomerListPage extends DefaultListable<Partner> implements INavigable {

    popover: any = null;

    constructor(
        public navCtrl: NavController,
        public loadingCtrl: LoadingController,
        public toastCtrl: ToastController,
        public popoverCtrl: PopoverController,
        public alertCtrl: AlertController,
        public db: DataProvider,
        public phone: PhoneProvider
    ) {
        super(loadingCtrl);
    }

    /**
     *
     */
    ionViewDidLoad() {
        this.initialize();
    }

    /**
     *
     */
    initialize(): void {
        let loader = this.loadingCtrl.create({
            content: "Cargando clientes, espere..."
        });
        loader.present();

        this.db.getAll(DataProvider.DOCS.PARTNER).then(partners => { 
            this.elements = partners.filter(item => {
                return item.customer = true && item.doc_state !== "deleted"; 
            });

            loader.dismiss();
        }).catch(e => {
            console.log(e);

            loader.dismiss();
            
            this.toastCtrl.create({
                message: "No se ha podido cargar los clientes",
                duration: 3000
            }).present();
        });
    }
    
    /**
     *
     */
    goToPage(page: any): void {
        this.navCtrl.push(CustomerDetailsPage, this);
    }

    /**
     *
     */
    showOptions(e, item) {
        this.popover = this.popoverCtrl.create(CustomerOptions);

        this.popover.present({
            ev: e
        });

        this.popover.onDidDismiss(data => {
            if (!data) {
                return;
            }

            switch (data.role) {
                case "open":
                    this.openItem(item);
                    break;
                case "delete":
                    this.askIfRemoveItem(item);
                    break;
                case "call":
                    this.askIfCall(item);
                    break;
                case "navigate":
                    this.askIfNavigate(item);
                    break;
                case "contact":
                    this.askIfSaveContact(item);
                    break;
            
                default:
                    this.openItem(item);
                    break;
            }
            
        });
    }

    /**
     *
     */
    openItem(item: any) {
        this.navCtrl.push(CustomerDetailsPage, item, data => {
            console.log(data);
        });
    }
    
     /**
     *
     */
    askIfRemoveItem(item): void {
        this.alertCtrl.create({
            title: "Confirmar",
            message: "Desea borrar este producto?",
            buttons: [
                {
                    text: "Cancelar",
                    handler: () => console.log("Canceled")
                },
                {
                    text: "Aceptar",
                    handler: () => this.removeItem(item)
                }
            ]
        }).present();
    }

    /**
     *
     */
    removeItem(item: any) {
        item.doc_state = "deleted";
        
        this.db.delete(DataProvider.DOCS.PRODUCT_TEMPLATE, item).then(result => this.remove(item)).catch(e => {
            console.log(e);
            
            this.toastCtrl.create({
                message: "No se pudo eliminar el producto",
                duration: 3000
            }).present();
        });
    }

        /**
     *
     */
    askIfCall(item: Partner): void {
        if (!item.mobile) {
            this.toastCtrl.create({
                message: "No hay contacto que llamar",
                duration: 3000
            }).present();

            return;
        }

        this.alertCtrl.create({
            title: "Confirmar",
            message: "Desea llamar al cliente?",
            buttons: [
                {
                    text: "Cancelar",
                    handler: () => {
                        console.log("Canceled");
                    }
                },
                {
                    text: "Aceptar",
                    handler: () => {
                        this.call(item);
                    }
                }
            ]
        }).present();
    }

    /**
     *
     */
    call(item: Partner): void {
        this.phone.call(item.mobile).subscribe(() => console.log("Dial opened"), e => console.log(e));
    }

    /**
     *
     */
    askIfNavigate(item: Partner): void {
        if (!item.partner_latitude || !item.partner_longitude) {
            this.toastCtrl.create({
                message: "No hay información para navegar",
                duration: 3000
            }).present();

            return;
        }

        this.alertCtrl.create({
            title: "Confirmar",
            message: "Desea navegar a la posición del cliente?",
            buttons: [
                {
                    text: "Cancelar",
                    handler: () => console.log("Canceled")
                },
                {
                    text: "Aceptar",
                    handler: () => this.navigate(item)
                }
            ]
        }).present();
    }

    /**
     *
     */
    navigate(item: Partner): void {
        this.phone.navigate(item.partner_latitude, item.partner_longitude).subscribe(() => {
            this.toastCtrl.create({
                message: "Abriendo aplicación",
                duration: 3000
            }).present();
        }, e => {
            console.log(e);
            
            this.toastCtrl.create({
                message: "No se pudo abrir la aplicación",
                duration: 3000
            }).present();
        });
    }

    /**
     *
     */
    askIfSaveContact(item: Partner): void {
        if (!item.phone && !item.phone && !item.mobile) {
            this.toastCtrl.create({
                message: "No hay información de contacto para guardar",
                duration: 3000
            }).present();

            return;
        }

        this.alertCtrl.create({
            title: "Confirmar",
            message: "Desea guardar el contacto en el teléfono?",
            buttons: [
                {
                    text: "Cancelar",
                    handler: () => console.log("Canceled")
                },
                {
                    text: "Aceptar",
                    handler: () => this.saveContact(item)
                }
            ]
        }).present();
    }

    /**
     *
     */
    saveContact(item: Partner): void {
        this.phone.saveContact(item.name, [item.mobile]).subscribe(() => {
            this.toastCtrl.create({
                message: "Contacto guardado en el teléfono",
                duration: 3000
            }).present();
        }, e => {
            console.log(e);

            this.toastCtrl.create({
                message: "Contacto guardado en el teléfono",
                duration: 3000
            }).present();
        });
    }
}
