// Copyright (C) 2020 - Today: GRAP (http://www.grap.coop)
// @author: Sylvain LE GAL (https://twitter.com/legalsylvain)
// License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

odoo.define("pos_meal_voucher.models", function (require) {
    "use strict";

    var models = require("point_of_sale.models");
    var utils = require("web.utils");
   
    var round_pr = utils.round_precision;

    models.load_fields("product.product", ["meal_voucher_ok"]);

    models.load_fields("account.journal", ["meal_voucher_type", "meal_voucher_mixed_text"]);

    var OrderSuper = models.Order.prototype;
    var Order = models.Order.extend({
                
        paper_meal_vouche_number_already_used: function(meal_voucher_number){
            for(const paiementLine of this.get_paymentlines()){
                if(paiementLine.statement_note == meal_voucher_number) return true
            }
            return false;
        },
        

        get_total_meal_voucher_eligible: function() {
            return round_pr(this.orderlines.reduce((function(sum, orderLine) {
                if (orderLine.product.meal_voucher_ok && orderLine.get_price_with_tax() > 0){
                    return sum + orderLine.get_price_with_tax();
                } else {
                    return sum;
                }
            }), 0), this.pos.currency.rounding);
        },
        get_total_meal_voucher_received: function(){
            return round_pr(this.paymentlines.reduce((function(sum, paymentLine) {
                if (paymentLine.is_meal_voucher()) {
                    return sum + paymentLine.get_amount();
                } else {
                    return sum;
                }
            }), 0), this.pos.currency.rounding);
        },
        is_meal_voucher_used: function() {
            var meal_voucher_used = false;
            this.paymentlines.each( function(paymentline) {                
                if (paymentline.is_meal_voucher()) {
                    meal_voucher_used = true;
                    return false;
                }
            });

            return meal_voucher_used;
        },
        /* point_of_sale/statis/src/js/models.js */
        export_for_printing: function(){
            var orderlines = [];
            var self = this;

            this.orderlines.each(function(orderline){
                var orderline_for_printing = orderline.export_for_printing();
                orderline_for_printing.product_meal_voucher_ok = orderline.product.meal_voucher_ok;

                orderlines.push(orderline_for_printing);
            });

            var paymentlines = [];
            this.paymentlines.each(function(paymentline){
                paymentlines.push(paymentline.export_for_printing());
            });
            var client  = this.get('client');
            var cashier = this.pos.cashier || this.pos.user;
            var company = this.pos.company;
            var shop    = this.pos.shop;
            var date    = new Date();
    
            function is_xml(subreceipt){
                return subreceipt ? (subreceipt.split('\n')[0].indexOf('<!DOCTYPE QWEB') >= 0) : false;
            }
    
            function render_xml(subreceipt){
                if (!is_xml(subreceipt)) {
                    return subreceipt;
                } else {
                    subreceipt = subreceipt.split('\n').slice(1).join('\n');
                    var qweb = new QWeb2.Engine();
                        qweb.debug = core.debug;
                        qweb.default_dict = _.clone(QWeb.default_dict);
                        qweb.add_template('<templates><t t-name="subreceipt">'+subreceipt+'</t></templates>');
                    
                    return qweb.render('subreceipt',{'pos':self.pos,'widget':self.pos.chrome,'order':self, 'receipt': receipt}) ;
                }
            }

            var receipt = {
                orderlines: orderlines,
                paymentlines: paymentlines,
                subtotal: this.get_subtotal(),
                total_with_tax: this.get_total_with_tax(),
                total_without_tax: this.get_total_without_tax(),
                total_tax: this.get_total_tax(),
                total_paid: this.get_total_paid(),
                total_discount: this.get_total_discount(),
                tax_details: this.get_tax_details(),
                change: this.get_change(),
                name : this.get_name(),
                client: client ? client.name : null ,
                invoice_id: null,   //TODO
                cashier: cashier ? cashier.name : null,
                precision: {
                    price: 2,
                    money: 2,
                    quantity: 3,
                },
                date: { 
                    year: date.getFullYear(), 
                    month: date.getMonth(), 
                    date: date.getDate(),       // day of the month 
                    day: date.getDay(),         // day of the week 
                    hour: date.getHours(), 
                    minute: date.getMinutes() ,
                    isostring: date.toISOString(),
                    localestring: date.toLocaleString(),
                }, 
                company:{
                    email: company.email,
                    website: company.website,
                    company_registry: company.company_registry,
                    contact_address: company.partner_id[1], 
                    vat: company.vat,
                    name: company.name,
                    phone: company.phone,
                    logo:  this.pos.company_logo_base64,
                },
                shop:{
                    name: shop.name,
                },
                currency: this.pos.currency,
                meal_voucher_used: this.is_meal_voucher_used(),
                total_meal_voucher_eligible: this.get_total_meal_voucher_eligible(),
                curtlery_img_src: " data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABsAAAAgCAQAAABJYMuwAAABI2lDQ1BJQ0MgcHJvZmlsZQAAKJGdkLFKw1AUhr+0oiLqYnEQhQyOFlzM5FIVgqAQYwWrU5qkWExiSFKKb+Cb6MN0EAQfwQdQcPa/0cHBLF44/B+Hc/7/3gstOwnTcm4X0qwqXL83uBxc2QtvtNlilQ47QVjmPc87ofF8vmIZfekar+a5P898FJehdKbKwryowNoXO9MqN6yic9v3D8UPYjtKs0j8JN6O0siw2fXTZBL+eJrbLMfZxbnpqzZxOeYUD5shE8YkVHSlmTpHOOxJXQoC7ikJpQmxelPNVNyISjm5HIj6It2mIW+jzvOUMpTHWF4m4Y5UniYP87/fax9n9aa1PsuDIqhbbVVrNIL3R1gZwNozLF03ZC3+flvDjFPP/PONXwa+UHRuacLOAAAACXBIWXMAAAsTAAALEwEAmpwYAAABWUlEQVQ4y93UTUvUURTH8c+9IyEygxoxi3KRVApBL6CHhSv3afsWSvgKqpcQbSpw0dYWBe7ciAtLwVWL1r6BVpI2yBRqDcdNTY7+/c8wi4guXLicc7/3d564KfS1ghGvPTYgm/PO1WDCstkQgmzKK6s2bNq04a3LIeOKW+4YVHHPdZO4adztlEgXPPHcXXU1VVU119xgoEM6deyUeOi+fDbGXJpB3YPiG+XYhNFiRzk2IvWDpfMcub+2/a5kzUVNoxhL2dj5Op3YsDdahvHIjEu9qlFth13vHmQun7syrOmowPO1m9pnH8/YD61FlOYWrfTMD9MqbeuOFz51zS0aFu2fsK5bj+i3JH8bi+7tLlpbnqqgbsFgz1g0vIc0bv7fLcn/iEWv2DfNE9CXU4O873v73LLXxqLppZ1f5g9WTonvWtQAB5Zsk/48m5Ih2VEcFn6Z2RAO4iccAzBJUmYVC7MHAAAAAElFTkSuQmCC"
            };
            
            if (is_xml(this.pos.config.receipt_header)){
                receipt.header = '';
                receipt.header_xml = render_xml(this.pos.config.receipt_header);
            } else {
                receipt.header = this.pos.config.receipt_header || '';
            }
    
            if (is_xml(this.pos.config.receipt_footer)){
                receipt.footer = '';
                receipt.footer_xml = render_xml(this.pos.config.receipt_footer);
            } else {
                receipt.footer = this.pos.config.receipt_footer || '';
            }
    
            return receipt;
        },
    });

    models.Order = Order;

    var PaymentlineSuper = models.Paymentline.prototype;

    var Paymentline = models.Paymentline.extend({

        initialize: function(){
            PaymentlineSuper.initialize.apply(this, arguments);
            // We use 'payment_note', because 'note' field is still used
            // to set in the payment_name value.
            // See odoo/addons/point_of_sale/models/pos_order.py:59
            // and then in the name of the statement line.
            // See odoo/addons/point_of_sale/models/pos_order.py:950
            this.statement_note = this.statement_note || '';
            this.meal_voucher_issuer = this.meal_voucher_issuer || '';
            this.manual_meal_voucher = this.manual_meal_voucher || false;
        },

        init_from_JSON: function (json) {
            PaymentlineSuper.init_from_JSON.apply(this, arguments);
            this.statement_note = json.statement_note;
            this.meal_voucher_issuer = json.meal_voucher_issuer;
        },
        export_as_JSON: function () {
            var res = PaymentlineSuper.export_as_JSON.apply(this, arguments);
            res.statement_note = this.statement_note;
            res.meal_voucher_issuer = this.meal_voucher_issuer;
            return res;
        },

        is_meal_voucher: function() {
            return (
                this.manual_meal_voucher === true ||
                ["paper", "dematerialized"].indexOf(
                    this.cashregister.journal.meal_voucher_type) !== -1
                );
        },
        is_dematerialized_meal_voucher: function() {
            return (
                this.cashregister.journal.meal_voucher_type == "dematerialized") ;
        },
        is_paper_meal_voucher: function() {
            return (
                this.cashregister.journal.meal_voucher_type == "paper") ;
        },
        set_meal_voucher_issuer: function(value){
            this.order.assert_editable();
            this.meal_voucher_issuer = value;
            this.trigger('change',this);
        },
    });

    models.Paymentline = Paymentline;

    var gui = require('point_of_sale.gui');
    var PopupWidget = require('point_of_sale.popups');

    var SelectOrTextInputPopupWidget = PopupWidget.extend({
        template: 'TextInputPopupWidget',
        show: function(options){
            options = options || {};
            this._super(options);

            this.renderElement();

            // On input change of value, reset select, and vice versa
            this.$("input").on("input", (e) => {
                if (e.target.value !== '') {
                    this.$("select").val('').change();
                }
            })
            this.$("select").on("change", (e) => {
                if (e.target.value !== '') {
                    this.$("input").val('');
                }
            })
        },
        click_confirm: function(){
            var value = 
                this.$('select').find(":selected").val() ? 
                this.$('select').find(":selected").val() : 
                this.$('input,textarea').val();

            // At least one field is mandatory
            if (value === '') {
                return;
            }

            this.gui.close_popup();
            if( this.options.confirm ){
                this.options.confirm.call(this,value);
            }
        },
    });
    gui.define_popup({name:'select-or-textinput', widget: SelectOrTextInputPopupWidget});
});