import { Component } from '@angular/core';
import { NavController, NavParams, ActionSheetController, ToastController, LoadingController, AlertController } from 'ionic-angular';
import { Product } from '../../models/product';
import { ProductListPage } from '../product-list/product-list';
import { DataProvider } from '../../providers/data-provider'
import { PhoneProvider } from '../../providers/phone-provider';
import { PreferencesProvider } from '../../providers/preferences-provider';

@Component({
    selector: 'page-product-details',
    providers: [ Product, PhoneProvider ],
    templateUrl: 'product-details.html'
})
export class ProductDetailsPage {

    attribute_lines: Array<any> = [];
    attribute_values: Array<any> = [];
    attributes: Array<any> = [];
    view: string = "information";
    watcher: any;

    constructor(
        public product: Product,
        public navCtrl: NavController,
        public params: NavParams,
        public data: DataProvider,
        public toastCtrl: ToastController,
        public actionSheetCtrl: ActionSheetController,
        public loadingCtrl: LoadingController,
        public alertCtrl: AlertController,
        public phone: PhoneProvider,
        public preferencesPreferences: PreferencesProvider
    ) { 
        if (!(this.params.data instanceof ProductListPage)) {
            this.product = this.params.data;
            this.product.doc_state = "updated";
        }
    }

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

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

    /**
     *
     */
    askIfScanBarcode(): void {
        this.alertCtrl.create({
            title: "Confirmar",
            message: "Desea escanear código de barras?",
            buttons: [
                {
                    text: "Cancelar",
                    handler: () => console.log("Canceled")
                },
                {
                    text: "Aceptar",
                    handler: () => this.scanBarcode()
                }
            ]
        }).present();
    }

    /**
     *
     */
    scanBarcode(): void {
        this.phone.scanBarcode().subscribe(barcode => { 
            this.product.ean13 = barcode.cancelled ? null : barcode.text;
        }, e => {
            console.log(e);
        
            this.toastCtrl.create({
                message: 'No se ha podido leer el código de barras',
                duration: 3000
            }).present();
        });
    }

    /**
     *
     */
    private isValidForm() {
        if (!this.product.name) {
            return false;
        }

        return true;
    }

    /**
     *
     */
    showPhotoOptions() {
        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();
    }

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

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

        this.data.getAll(DataProvider.DOCS.PRODUCT_ATTRIBUTE_LINE).then(product_attribute_lines => {
            this.attribute_lines = product_attribute_lines;

            return this.data.getAll(DataProvider.DOCS.PRODUCT_ATTRIBUTE);
        }).then(product_attributes => {
            this.attributes = product_attributes;

            return this.data.getAll(DataProvider.DOCS.PRODUCT_ATTRIBUTE_VALUE);
        }).then(product_attribute_values => {
            this.attribute_values = product_attribute_values;

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

    /**
     *
     */
    addAttribute(): void {
        if (!this.product.attribute_line_ids) {
            this.product.attribute_line_ids = [];
        }
        
        this.product.attribute_line_ids.push({
            attribute: 1,
            value: 1
        });
    }

    /**
     *
     */
    saveAttributeValues(attribute_id, attribute_values) {
        let attribute_line = this.attribute_lines.filter(item => {
            return this.product.attribute_line_ids.indexOf(item.remote_id) > -1 && item.attribute_id === attribute_id;
        })[0];

        attribute_line.value_ids = attribute_values;
        attribute_line.doc_state = "updated";
        
        this.data.save(DataProvider.DOCS.PRODUCT_ATTRIBUTE_LINE, attribute_line).then(pal => { 
            console.log(pal);           
        }, e => { 
            this.toastCtrl.create({
                message: "No se han podido guardar los cambios",
                duration: 3000
            }).present();
        });
    }

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

        this.data.save(DataProvider.DOCS.PRODUCT_TEMPLATE, this.product).then(product => {
            if (this.params.data instanceof ProductListPage) {
                this.params.data.add(product);
            }
            
            this.navCtrl.pop(this);
        }).catch(e => {
            console.log(e);
            
            this.toastCtrl.create({
                message: 'No se han podido guardar los cambios',
                duration: 3000
            }).present();

        });
  
    }
}
