import { Component } from '@angular/core';
import { NavController, NavParams, ActionSheetController, AlertController } from 'ionic-angular';

import { SaleOrder } from "../../odoo/models/sale.order";
import { Partner } from "../../odoo/models/res.partner";
import { ProductProduct } from "../../odoo/models/product.product";
import { BaseDetailsView } from "../../base/base-details-view";

import { CustomersPage } from "../customers/customers";
import { VariantsPage } from "../variants/variants";

import { Cart } from "./models/cart";
import { CartItem } from "./models/cart-item"

import { EventsManager } from "../../base/events/event-manager";

@Component({
    selector: 'page-order',
    templateUrl: 'order.html'
})
export class OrderPage extends BaseDetailsView<SaleOrder> {

    cart: Cart;

    constructor(
        public navCtrl: NavController,
        public navParams: NavParams,
        public actionSheetCtrl: ActionSheetController,
        public alertCtrl: AlertController
    ) { 
        super(SaleOrder, navParams.data.item, navParams.data.kind);

        let titleKind = super.getKind() === "budget" ? "Presupuesto" : "Venta";
        super.setTitle(super.itemExists() ? "Editar " + titleKind : "Crear " + titleKind);

        this.cart = new Cart();
    }

    /**
     * 
     */
    ionViewDidLoad() {
        EventsManager.subscribe("app:select", data => { 
            if (data.type instanceof Partner) {
                this.setCustomer(data.item);
            }

            if (data.type instanceof ProductProduct) {
                this.addProduct(data.item);
            }
        });
    }

    /**
     * 
     */
    getCart(): Cart {
        return this.cart;
    }

    /**
     * 
     */
    getCustomer(): Partner {
        return this.getCart().getCustomer();
    }

    /**
     * 
     */
    getCustomerName(): string {
        return this.getCustomer() ? this.getCustomer().name : "";
    }

    /**
     * 
     */
    getItems(): Array<CartItem> {
        return this.getCart().getItems();
    }

    /**
     * 
     */
    getTotal(): number {
        return this.getCart().getTotal();
    }

    /**
     * 
     * @param cart 
     */
    setCart(cart: Cart): void {
        this.cart = cart;
    }

    /**
     * 
     * @param customer 
     */
    setCustomer(customer: Partner): void {
        this.getCart().setCustomer(customer);
    }

    /**
     * 
     */
    selectCustomer(): void {
        this.navCtrl.push(CustomersPage, { 
            params: {
                mode: "selection"
            }
        });
    }

    /**
     * 
     */
    selectProduct(): void {
        this.navCtrl.push(VariantsPage, { 
            params: {
                mode: "selection"
            }
        });
    }

    /**
     * 
     * @param product 
     */
    addProduct(product: ProductProduct): void {
        this.getCart().add(product, product.list_price, 1);
    }

    /**
     * 
     * @param item 
     * @param quantity 
     */
    updateQuantity(item: CartItem, quantity: number): void {
        if ((item.getQuantity() + quantity) <= 0) {
            this.askIfRemove(item);
            return;
        }

        item.updateQuantity(quantity);
        this.cart.updateTotal();
    }

    /**
     * 
     * @param item 
     * @param price 
     */
    updatePrice(item: CartItem, price: number): void {
        item.updatePrice(price);
        this.cart.updateTotal();
    }
    
    /**
     * 
     */
    openBarcodeReader(): void {
    }

    /**
     * 
     */
    openOptions(item: any): void {
        this.actionSheetCtrl.create({
            title: "Opciones",
            buttons: [
                {
                    text: "Aplicar descuento",
                    icon: "calculator",
                    handler: () => {
                        this.showDiscount(item);
                    }
                },
                {
                    text: "Agregar cantidad",
                    icon: "cart",
                    handler: () => {
                        this.showQuantity(item);
                    }
                },
                {
                    text: "Borrar",
                    icon: "remove",
                    handler: () => {
                        this.askIfRemove(item);
                    }
                },
                {
                    text: "Cancelar",
                    role: "cancel"
                }
            ]
        }).present();
    }

    /**
     * 
     * @param item 
     */
    showDiscount(item: any): void {
        this.alertCtrl.create({
            title: "Descuento",
            inputs: [
                {
                    name: "discount",
                    type: "number",
                    value: item.price
                }
            ],
            buttons: [
                {
                    text: "Cancelar"
                },
                {
                    text: "Aceptar",
                    handler: (e) => {
                        this.updatePrice(item, e.discount);
                    }
                }
            ]
        }).present();
    }

    /**
     * 
     * @param item 
     */
    showQuantity(item: any): void {
        this.alertCtrl.create({
            title: "Cantidad",
            inputs: [
                {
                    name: "quantity",
                    type: "number",
                    value: item.qty
                }
            ],
            buttons: [
                {
                    text: "Cancelar"
                },
                {
                    text: "Aceptar",
                    handler: (e) => {
                        this.updateQuantity(item, e.quantity);
                    }
                }
            ]
        }).present();
    }

    /**
     * 
     */
    askIfRemove(item: any): void {
        this.alertCtrl.create({
            title: "Borrar producto",
            buttons: [
                {
                    text: "Cancelar"
                },
                {
                    text: "Aceptar",
                    handler: () => {
                        this.removeFromCart(item);
                    }
                }
            ]
        }).present();
    }

    /**
     * 
     * @param item 
     */
    removeFromCart(item: CartItem): void {
        this.cart.remove(item);
    }

    /**
     * 
     * @param data 
     */
    submit() { 
        this.getCart().toOdoo();
    }
}
