/*jslint node: true */
/*jslint browser: true*/
/*jslint nomen: true*/
/*global BaseController, angular, $*/

'use strict';

var dataTransferController = BaseController.extend({
    /**
     * Initialize  Controller
     * @param $scope, current controller scope
     */
    init: function ($scope, $rootScope, $timeout, $modal, dataTransferService) {
        this._super($scope);
        this.$modal = $modal;
        this.$timeout = $timeout;
        this.dataTransferService = dataTransferService;

        this.$scope.exportObjects = {};
        this.$scope.exportCategories = {};
        this.$scope.importFormData = {};
        this.$scope.dataToImport = false;
        this.$scope.seletedFile = false;
        this.$scope.exportOnlyUserItems = false;
        this.$scope.showEncryptionKeyField = {export: false, import: false};
        this.$scope.skipDuplicates = 1;
        this.$scope.encryptionKey = {export: '', import: ''};


        let self = this;
        common.globalSpinner.show();
        this.dataTransferService.getExportItems().then(function (response) {
            common.globalSpinner.hide();
            self.$scope.exportCategories = response.data;
        }).catch(function (error) {
            self.showError(error.data);
            common.globalSpinner.hide();
        });

    },

    defineScope: function () {
        this.$scope.instance = "indexController";
        this.$scope.export = this.export.bind(this);
        this.$scope.import = this.import.bind(this);
        this.$scope.onFileSelected = this.onFileSelected.bind(this);
        this.$scope.selectAllExportItems = this.selectAllExportItems.bind(this);
        this.$scope.cancelImport = this.cancelImport.bind(this);
        this.$scope.generateEncryptionKey = this.generateEncryptionKey.bind(this);
    },
    defineListeners: function () {
        var self = this;

        this.$scope.$watchCollection('exportObjects', function (value) {

            //delete unselected options
            Object.keys(self.$scope.exportObjects).forEach(function (value, index) {
              if(self.$scope.exportObjects[value] == false) {
                  delete self.$scope.exportObjects[value];
              }
            })

            if (value.settingsVCS == true || value.settingsAuthentication == true || value.settingsMail == true || value.users == true) {
                self.$scope.showEncryptionKeyField.export = true;
            } else {
                self.$scope.showEncryptionKeyField.export = false;
            }
        });

        this.$scope.$watchCollection('dataToImport', function (value) {
            if (value == false) {
                return;
            }

            if (value.hasOwnProperty('settingsVCS') || value.hasOwnProperty('settingsAuthentication') || value.hasOwnProperty('settingsMail') || value.hasOwnProperty('users')) {
                self.$scope.showEncryptionKeyField.import = true;
            } else {
                self.$scope.showEncryptionKeyField.import = false;
            }
        });
    },
    export: function () {
        let self = this;
        common.globalSpinner.show();
        this.dataTransferService.export(Object.keys(self.$scope.exportObjects), this.$scope.exportOnlyUserItems, this.$scope.encryptionKey.export).then(function (response) {
            common.globalSpinner.hide();
            document.location.href = '/data_transfer/api/download/' + response.data.name;
        }).catch(function (error) {
            self.showError(error.data);
            common.globalSpinner.hide();
        });
    },
    onFileSelected: function (file) {
        common.globalSpinner.show()
        let self = this;
        let formData = new FormData();
        formData.append('file', file);
        self.$scope.seletedFile = file;
        this.dataTransferService.analyzeImportFile(formData).then(function (response) {
            self.$scope.dataToImport = response.data;
            common.globalSpinner.hide();
        }).catch(function (error) {
            self.showError(error.data);
            common.globalSpinner.hide();
        });
    },
    import: function () {
        common.globalSpinner.show();
        let self = this;
        let formData = new FormData();
        formData.append('file', self.$scope.seletedFile);
        formData.append('skipDuplicates', self.$scope.skipDuplicates);
        formData.append('encryptionKey', this.$scope.encryptionKey.import);
        this.dataTransferService.makeImport(formData).then(function (response) {
            common.globalSpinner.hide();
            notify.success("Import successfully done.");
        }).catch(function (error) {
            self.showError(error.data);
            common.globalSpinner.hide();
        });
    },
    showError: function (message) {
        notify.error(message);
    },
    cancelImport: function () {
        this.$scope.dataToImport = false;
        this.$scope.seletedFile = false;
        this.$scope.importFormData = {};
        //clear input form
        angular.forEach(
            angular.element("input[type='file']"),
            function (inputElem) {
                angular.element(inputElem).val(null);
            }
        );

    },
    selectAllExportItems: function () {
        let self = this;

        Object.keys(self.$scope.exportCategories).forEach(function (value, key) {
            self.$scope.exportObjects[self.$scope.exportCategories[value].id] = true;
        });
    },
    generateEncryptionKey: function () {
        this.$scope.encryptionKey.export = common.generateRandomString(60);
    }
});


dataTransferController.$inject = ['$scope', '$rootScope', '$timeout', '$modal', 'dataTransferService'];

dataTransferApp.controller('dataTransferController', dataTransferController);