(function () {
    'use strict';
    window.CEAuth = getEAuth();

    function getEAuth () {
        function EAuth () {
            var self = this;

            // this.certificates = [];

            this.formClass = 'p-1'
            this.inpClass = 'py-3 px-4 bg-white rounded-lg placeholder-gray-400 text-gray-900 appearance-none inline-block w-full shadow-md mt-2 focus:outline-none focus:ring-2 focus:ring-blue-600';
        
            
            this.text = {
                edpAuthTitle: 'ЭЦП',
                didoxAuthTitle: 'Войти с DIDOX',
                didoxAuthLogin: 'ИНН',
                didoxAuthPassword: 'Пароль',
                authByDidox: 'DIDOX',
                authByEdp: 'Войти с ЭЦП',

                errorCAPIWS: 'Ошибка соединения с E-IMZO. Возможно у вас не установлен модуль E-IMZO или Браузер E-IMZO.'
            }

            // this.getEDP(
            //     function (arr) {
            //         self.certificates = arr;
            //     }, function () {
                    
            //     }, function () {

            //     }
            // );
        }

        EAuth.prototype = {
            init: function () {
                var self = this;
                var keys = App.getAuthTokens();
                var sInfo = AppStorage.get(App.storage.authInfo.key);
                var opt = [];

                if (!keys.length && !sInfo.data) {
                    return;
                }

                if (sInfo.data) {
                    $('#auth_container').show();
                    $('#auth_select').html('');
                    $('#auth_select').append('<option>'+sInfo.data+'</option>');
                }
            },

            call: function (isCV, onConfirm) {
                var self = this;


                if (isCV) {
                    EIMZOClient.installApiKeys(function () {
                        self.EDPAuth({
                                showDidoxAuth: true,
                                onConfirm: onConfirm,
                                onTokenLoad: self._onTokenLoad.bind(self)
                            })
                    }, function (e, r) {
                        if (r) {
                            self._uiShowMessage(r);
                        } else {
                            self._wsError(e);
                        }
                        this.didoxAuth({
                            showEdpAuth: false,
                            onConfirm: onConfirm,
                            onTokenLoad: self._onTokenLoad.bind(self)
                        });
                    });
                } else {
                    this.didoxAuth({
                        showEdpAuth: false,
                        onConfirm: onConfirm,
                        onTokenLoad: self._onTokenLoad.bind(self)
                    });
                }
            },

            EDPAuth: function (p) {
                var self = this, 
                    options = {
                        html: '<form class="p-1">' + 
                            '<select id="key" class="'+this.inpClass+'"></select>'+
                        '</form>',
                        didOpen: function () {
                            self._loadkeys();
                        }
                    };

                if (p.showDidoxAuth) {
                    options.showCancelButton = true;
                    options.cancelButtonText = this.text.authByDidox;
                }

                Swal.fire(options).then(function (params) {
                    var itm = (self._getSelect()).value;

                    if (params.isConfirmed && itm) {
                        var id = document.getElementById(itm);
                        var vo = JSON.parse(id.getAttribute('vo'));

                        p.onConfirm({
                            vo: vo,
                            auth: null,
                            // onTokenLoaded: function () {
                            //     // AppStorage.set(App.storage.authInfo.key + '_' + vo.serialNumber, {
                            //     //     sn: vo.serialNumber
                            //     // });
                            // },
                        });
                    } else if (params.isDismissed && params.dismiss === 'cancel') {
                        self.didoxAuth({
                            showEdpAuth: true,
                            onConfirm: p.onConfirm
                        });
                    }
                });
            },

            didoxAuth: function (p) {
                var self = this,
                    options = {
                        html: '<form class="p-1">' + 
                            '<h3>'+self.text.didoxAuthTitle+'</h3>' +
                            '<input type="text" class="'+this.inpClass+'" placeholder="'+this.text.didoxAuthLogin+'" id="d_tin">' +
                            '<input type="password" class="'+this.inpClass+'" placeholder="'+this.text.didoxAuthPassword+'" autocomplete="off" id="d_password">' +
                        '</form>'
                    };
                var sData = this.checkDidoxAuth();

                if (sData) {
                    p.onConfirm({
                        vo: null,
                        auth: sData,
                        // onTokenLoaded: 0
                    });
                    return;
                }
                
                if (p.showEdpAuth) {
                    options.showCancelButton = true;
                    options.cancelButtonText = this.text.edpAuthTitle;
                }
                
                Swal.fire(options).then(function (params) {
                    if (params.isConfirmed) {
                        var tin = document.querySelector('#d_tin').value;
                        var password = document.querySelector('#d_password').value;

                        p.onConfirm({
                            vo: null,
                            auth: {
                                tin: tin,
                                password: password,
                                token: ''
                            },
                            onTokenLoaded: function () {
                                AppStorage.set(App.storage.authInfo.key, tin);
                            }
                        });
                    } else if (params.isDismissed && params.dismiss === 'cancel') {
                        self.EDPAuth({
                            showDidoxAuth: true,
                            onConfirm: p.onConfirm
                        });
                    }
                });
            },

            checkDidoxAuth: function () {
                var sToken = AppStorage.get(App.storage.didoxToken.key);
                var sTin = AppStorage.get(App.storage.authInfo.key);

                if (
                    App.checkSavedData(sToken, App.storage.didoxToken.limit) && sTin.data
                ) {
                    return {
                        tin: sTin.data.tin,
                        token: sToken.data
                    }                    
                }

                return null;
            },

            isTokenActive: function (token, limit) {
                return token.data && this.checkValid(new Date(), token.date, limit);
            },




            _uiShowMessage: function (msg) {
                App.showMessage(msg);
            },
            _wsError: function (e) {
                DocSign._wsError(e);
            },
            _loadkeys: function () {
                var self = this;

                EIMZOClient.listAllUserKeys(function (o, i) {
                    var itemId = "itm-" + o.serialNumber + "-" + i;
                    return itemId;
                }, function (itemId, v) {
                    return self._createItem(itemId, v);
                }, function (items, firstId) {
                    self._fillCombo(items);
                    self._comboSelect(firstId);
                }, function (e, r) {
                    App.showMessage(self.text.errorCAPIWS);
                });
            },
            _createItem: function (itmkey, vo) {
                var now = new Date();
                vo.expired = dates.compare(now, vo.validTo) > 0;
                var itm = document.createElement("option");
                itm.value = itmkey;
                itm.text = vo.CN;
                if (!vo.expired) {
        
                } else {
                    itm.style.color = 'gray';
                    itm.text = itm.text + ' (срок истек)';
                }
                itm.setAttribute('vo', JSON.stringify(vo));
                itm.setAttribute('id', itmkey);
                return itm;
            },
            _fillCombo: function (items) {
                var combo = this._getSelect();
                for (var itm in items) {
                    combo.append(items[itm]);
                }
            },
            _comboSelect: function (itm) {
                if (itm) {
                    var id = document.getElementById(itm);
                    id.setAttribute('selected', 'true');
                }
            },
            _getSelect: function () {
                return document.getElementById('key');
            },
            // getEDP: function (success, error, fail) {
            //     if (typeof CAPIWS === 'undefined') {
            //         return fail();
            //     }
            //     CAPIWS.callFunction({plugin: 'pfx', name: 'list_all_certificates'}, function (event, data) {
            //         if (data.success) {
            //             var res = [];
            //             for (var rec in data.certificates) {
            //                 var el = data.certificates[rec];
            //                 var x500name_ex = el.alias.toUpperCase();
            //                 x500name_ex = x500name_ex.replace("1.2.860.3.16.1.1=", "INN=");
            //                 x500name_ex = x500name_ex.replace("1.2.860.3.16.1.2=", "PINFL=");
            //                 var vo = {
            //                     disk: el.disk,
            //                     path: el.path,
            //                     name: el.name,
            //                     alias: el.alias,
            //                     serialNumber: EIMZOClient._getX500Val(x500name_ex, "SERIALNUMBER"),
            //                     validFrom: new Date(EIMZOClient._getX500Val(x500name_ex, "VALIDFROM").replace(/\./g, "-").replace(" ", "T")),
            //                     validTo: new Date(EIMZOClient._getX500Val(x500name_ex, "VALIDTO").replace(/\./g, "-").replace(" ", "T")),
            //                     CN: EIMZOClient._getX500Val(x500name_ex, "CN"),
            //                     TIN: (EIMZOClient._getX500Val(x500name_ex, "INN") ? EIMZOClient._getX500Val(x500name_ex, "INN") : EIMZOClient._getX500Val(x500name_ex, "UID")),
            //                     UID: EIMZOClient._getX500Val(x500name_ex, "UID"),
            //                     PINFL: EIMZOClient._getX500Val(x500name_ex, "PINFL"),
            //                     O: EIMZOClient._getX500Val(x500name_ex, "O"),
            //                     T: EIMZOClient._getX500Val(x500name_ex, "T"),
            //                     type: 'pfx'
            //                 };

            //                 res.push(vo);
            //             }
            //             success(vo);
            //         } else {
            //             error(data);
            //         }
                    
            //     }, function (e) {
            //         fail(e);
            //     });
            // },

            _onTokenLoad: function (vo, auth, token) {
                if (vo) {
                    AppStorage.set('auth_info' + '_' + vo.serialNumber, vo.TIN);
                } else if (auth) {
                    AppStorage.set('auth_info' + '_' + auth.tin, auth.tin);
                }
            }
        }

        return EAuth;
    }
})();