/*
    © 2020 Le Filament (<http://www.le-filament.com>)
    License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

*/


odoo.define('vracoop_pos_container_qrcode.container_print_qr', function (require) {
    "use strict";

    var chrome = require('point_of_sale.chrome');
    var gui = require('point_of_sale.gui');
    var models = require('point_of_sale.models');
    var screens = require('point_of_sale.screens');
    var popups = require('point_of_sale.popups');   
    var container = require('pos_container.container');

    var core = require('web.core');
    var rpc = require('web.rpc');
    var utils = require('web.utils');
    var QWeb = core.qweb;
    var _t = core._t;

    var round_pr = utils.round_precision;
    var action_button_classes = [];

    var BalanceContainerQRScreenWidget = screens.ScaleScreenWidget.extend({
        template: 'BalanceContainerQRScreenWidget',

        init: function(parent, options){
            this._super(parent, options);
            this.barcode_base64;
        },

        show: function(){
            
            var self = this;
            var queue = this.pos.proxy_queue;
            var priceStr = '001000'; // bizerba doesn't accept '000000' as unit price
            this.renderElement();
            queue.schedule(function () {
                return self.pos.proxy.reset_weight().then(function () {
                    self.set_weight(0);
                });
            }, {duration: 500});

            var count_it = 0;
            queue.schedule(function () {
                return self.pos.proxy.scale_read_data_price(priceStr).then(function (scale_answer) {
                    
                    if (count_it < 4) {
                        count_it += 1;
                    }
                    else {
                        count_it = 0;
                        if (self.weight > 0){
                            self.print();
                            self.gui.show_screen('confirmation');
                        }
                    }
                    self.set_weight(scale_answer.weight);
                    if ((scale_answer.error === '30' || scale_answer.error === '31') && scale_answer.weight !== 0) {
                        self.set_weight(0);
                    }
                });

            }, {duration: 500, repeat: true});
            
            this._super();

            var self = this;

            if(this.pos.config.iface_vkeyboard && this.chrome.widget.keyboard){
                this.chrome.widget.keyboard.connect($(this.el.querySelector('.container-name input')));
            }

            $("#pos-header-text-peser").removeClass('oe_hidden');
            $("#pos-topheader-scale-cont").removeClass('oe_hidden');

        },

        hide: function(){
            this._super();
            $("#pos-header-text-peser").addClass('oe_hidden');
            $("#pos-topheader-scale-cont").addClass('oe_hidden');
        },

        /////////////////////////////
        // Begin Function to Print //
        /////////////////////////////

        handle_auto_print: function() {
            this.print();
            this.click_next();
        },

        lock_screen: function(locked) {
            this._locked = locked;
            if (locked) {
                this.$('.next').removeClass('highlight');
                this.$('.top-content').addClass('highlight');
            } else {
                this.$('.next').addClass('highlight');
                this.$('.top-content').removeClass('highlight');
            }
        },

        get_receipt_render_env: function() {
            var url_qr = this.pos.config.url_qrcode;
            var categ_container = this.pos.config.categ_container;
            var timestamp = Math.floor((new Date().getTime())/1000);

            var weight_str = (this.weight * 1000).toString();
            weight_str = ("0000" + weight_str).slice(-4);

            var prefixe_qr = ("00000" + this.pos.config.prefixe_qr).slice(-5);

//            Construction du code à 21 chiffres (timestamp+catégorie+num émetteur+poids)
            var ean19 = '';
            ean19 = ean19.concat(timestamp.toString(),categ_container,prefixe_qr,weight_str);

//            Calcul de la clé de Luhn
            var ean20 = this.pos.barcode_reader.barcode_parser.sanitize_ean19(ean19);

//            Récupération de chaque partie pour convertir en base 36
            var first_int = parseInt(ean20.substring(0,10));
            var second_int = parseInt(ean20.substring(10,21));
            var cle_int = parseInt(ean20.substr(-1));

//            Conversion bae 36
            var base36_first = first_int.toString(36);
            var base36_second = second_int.toString(36);
            var base36_cle = cle_int.toString(36);

            var url_qrcode = url_qr.concat(base36_cle,'-',base36_first,'-',base36_second);
            var weight_gr = parseInt(weight_str, 10) + 'g'
            return {    
                widget: this,
                weight: this.weight,
                url_barcode: url_qrcode,
                weight_gr: weight_gr
            }
       
        },

        renderElement: function() {
            var self = this;
            this._super();
            
            this.$('.next,.print-qrcode').click(function(){
                self.print();
            });
        },

        print_web: function() {
            if ($.browser.safari) {
                document.execCommand('print', false, null);
            } else {
                try {
                    window.print();
                } catch(err) {
                    if (navigator.userAgent.toLowerCase().indexOf("android") > -1) {
                        this.gui.show_popup('error',{
                            'title':_t('Printing is not supported on some android browsers'),
                            'body': _t('Printing is not supported on some android browsers due to no default printing protocol is available. It is possible to print your tickets by making use of an IoT Box.'),
                        });
                    } else {
                        throw err;
                    }
                }
            }
        },
        print_xml: function() {
            
            var receipt = QWeb.render('XmlQR', this.get_receipt_render_env());
            this.pos.proxy.print_receipt(receipt);

            
        },
        print: function() {
            var self = this;

            if (!this.pos.config.iface_print_qr_via_proxy) { // browser (html) printing

                this.lock_screen(true);

                setTimeout(function(){
                    self.lock_screen(false);
                }, 1000);

                this.print_web();
            } else {    // proxy (xml) printing
                this.print_xml();
                this.lock_screen(false);
            }
        },
        click_next: function() {
            this.set_weight(0);
        },
        click_back: function() {
            this.set_weight(0);
        },
        render_receipt: function() {
            this.$('.pos-qr-container').html(QWeb.render('PosQR', this.get_receipt_render_env()));
        },

        /////////////////////////////
        // End Function to Print //
        /////////////////////////////

        close: function(){
            this._super();
            if (this.pos.config.iface_vkeyboard && this.chrome.widget.keyboard) {
                this.chrome.widget.keyboard.hide();
            }
        },
    });

    gui.define_screen({
        'name':'balancecontainerqr',
        'widget': BalanceContainerQRScreenWidget,
        'condition': function(){
            return this.pos.config.is_print_container_qr;
        },
    });

    var ConfirmationScreen = screens.ScreenWidget.extend({
        template: 'ConfirmationScreen',

        next_screen: 'balancecontainerqr',

        show: function(){
            
            this._super();
            var self = this;      
            
            setTimeout(function(){
                self.gui.show_screen('balancecontainerqr');
            }, 5000);

        },

    });

    gui.define_screen({
        'name': 'confirmation',
        'widget': ConfirmationScreen,
        'condition': function(){
            return this.pos.config.is_print_container_qr;
        },
    });


    // Add the Balance print QR Code to the GUI, and set it as the default screen
    chrome.Chrome.include({
        build_widgets: function(){
            this._super();
            if (this.pos.config.is_print_container_qr) {
                this.gui.set_startup_screen('balancecontainerqr');
            }
        },

        build_chrome: function() {
            this._super();
            var self = this;
            if (this.pos.config.is_print_container_qr) {
                this.$('.pos-topheader').addClass('oe_hidden');
                this.$('.close-button-bls').click(function(){
                    self.click_close();
                });
            }
            else {
                this.$('.pos-topheader-title').addClass('oe_hidden');
            }

        },

        click_close: function() {
            var self = this;
            clearTimeout(this.confirmed);
            this.gui.close();
        },

    });

    gui.Gui.include({
        show_saved_screen:  function(order,options) {
            this._super();
            options = options || {};
            this.close_popup();
            this.show_screen(this.startup_screen);
        },
    });

    // We need to modify the OrderSelector to hide itself when we're on
    // the floor plan ?
    chrome.OrderSelectorWidget.include({
        
        hide: function(){
            this.$el.addClass('oe_invisible');
        },
        show: function(){
            this.$el.removeClass('oe_invisible');
        },
        renderElement: function(){
            var self = this;
            this._super();
            if (this.pos.config.is_print_container_qr) {
                if (this.pos.get_order()) {
                    this.$el.removeClass('oe_invisible');
                } else {
                    this.$el.addClass('oe_invisible');
                }
            }
        },

    });

    return {
        BalanceContainerQRScreenWidget: BalanceContainerQRScreenWidget,
    };

});