/* globals chrome */

(() => {
  'use strict';
  angular.module('app', [])
    .controller('appCtrl', ['$scope', '$timeout', function AppCtrl ($scope, $timeout) {
      const vm = this;
      vm.options = {};
      vm.tab = 0;

      const fileInput = document.getElementById('file-input');
      fileInput.addEventListener('change', (e) => {
        vm.importData(e);
      });

      vm.$onInit = async () => {
        await vm.load();
        if (!vm.options.pasteEmailList || !vm.options.pasteEmailList.length) {
          vm.options.pasteEmailList = [''];
        }
        if (!vm.options.autocompleteEmailList || !vm.options.autocompleteEmailList.length) {
          vm.options.autocompleteEmailList = [''];
        }
        $timeout(() => {
          $scope.$apply();
        });
      };

      vm.changeTab = (tab) => {
        vm.tab = tab;
      };

      vm.updateEmailList = () => {
        vm.save(angular.copy(vm.options));
      };

      vm.addEmail = (list) => {
        vm.options[list].push('');
        $timeout(() => {
          const inputs = document.querySelectorAll('.option-block .email input');
          const lastInput = inputs.at(-1);
          if (lastInput) {
            lastInput.focus();
          }
        });
      };

      vm.removeEmail = (list, index) => {
        vm.options[list].splice(index, 1);
        if (!vm.options[list].length) {
          vm.options[list] = [''];
        }
        vm.updateEmailList();
      };

      vm.clearAll = (list) => {
        if (confirm('האם למחוק את כל הרשימה?')) {
          vm.options[list] = [''];
          vm.updateEmailList();
        }
      };

      // Load options from storage
      vm.load = () => {
        return new Promise((resolve, reject) => {
          chrome.storage.sync.get('options', (storage) => {
            // Get and save options
            vm.options = storage.options || {};
            resolve(vm.options);
          });
        });
      };

      // Save options to storage
      vm.save = (object) => {
        object.pasteEmailList = vm.options.pasteEmailList.filter(Boolean);
        object.autocompleteEmailList = vm.options.autocompleteEmailList.filter(Boolean);

        return new Promise((resolve) => {
          chrome.storage.sync.set({
            options: object
          }, resolve);
        });
      };

      vm.exportData = () => {
        const fileName = `email-autocomplete-backup-${new Date().toLocaleDateString()}.json`;
        const data = { pasteEmailList: vm.options.pasteEmailList, autocompleteEmailList: vm.options.autocompleteEmailList };
        const a = document.createElement('a');
        document.body.appendChild(a);
        a.style = 'display: none';
        const json = JSON.stringify(data);

        const blob = new Blob([json], { type: 'octet/stream' });

        const url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = fileName;
        a.click();
        window.URL.revokeObjectURL(url);
      };

      vm.importFile = () => {
        fileInput.click();
      };

      vm.importData = () => {
        let success;
        let stopTimeOut;
        const file = fileInput.files[0];
        const textType = 'application/json';
        if (!file) {
          return;
        }

        const exportDataElement = document.querySelector('.export-data');
        if (file.type.match(textType)) {
          const reader = new FileReader();

          reader.onload = (e) => {
            const content = reader.result;
            try {
              const settings = JSON.parse(content);

              if (angular.isObject(settings.pasteEmailList) || angular.isObject(settings.autocompleteEmailList)) {
                if (angular.isObject(settings.pasteEmailList)) {
                  vm.options.pasteEmailList = settings.pasteEmailList;
                }
                if (angular.isObject(settings.autocompleteEmailList)) {
                  vm.options.autocompleteEmailList = settings.autocompleteEmailList;
                }
                vm.updateEmailList();
                success = true;
              } else {
                success = false;
              }
            } catch (error) {
              success = false;
            }

            if (success === true) {
              exportDataElement.innerHTML = '<i class="zmdi zmdi-check"></i> שחזור הושלם';
            } else if (success === false) {
              exportDataElement.innerHTML = '<i class="zmdi zmdi-close"></i> שחזור לא הושלם';
            }
            if (stopTimeOut) { clearTimeout(stopTimeOut); }
            stopTimeOut = setTimeout(() => {
              exportDataElement.innerHTML = 'ייבוא הגדרות';
            }, 3000);
          };

          reader.readAsText(file);
        } else {
          success = false;
        }

        if (success === false) {
          exportDataElement.innerHTML = '<i class="zmdi zmdi-close"></i> שחזור לא הושלם';

          if (stopTimeOut) { clearTimeout(stopTimeOut); }
          stopTimeOut = setTimeout(() => {
            exportDataElement.innerHTML = 'ייבוא הגדרות';
          }, 3000);
        }
      };
    }]);
})();
