'use strict';

var editController = BaseController.extend({

    /**
     * Initialize  Controller
     * @param $scope, current controller scope
     */
    init: function($scope, $location, $routeParams, reportService, wizardSharedService, commonHelper, sqlHelper, notificationService, paginationService, modalWindowService, hubManagementService) {
        var self = this;
        this._super($scope);
        self.$scope = $scope;

        this.$location            = $location;
        this._reportService       = reportService;
        this._wizardSharedService = wizardSharedService;
        this._commonHelper        = commonHelper;
        this._sqlHelper           = sqlHelper;
        this._notificationService = notificationService;

        this.$scope.paginator     = paginationService;
        this.$scope.modalWindow   = modalWindowService;

        hubManagementService.gethubStatus().then(function (status) {
            if (status.data.configured !== undefined && status.data.configured === true && status.data.role === 'superhub') {
                self._commonHelper.includeHubIdIntoDCA();
                self._restoreScopes();
            }
        })

        self.$scope.reportId    = '';
        self.$scope.reportLabel = '';
        self.$scope.reportRoles = {};
        self.$scope.modalData = {};
        self.$scope.joinTypes = {
            main: 'main',
            left: 'leftJoin',
            inner: 'innerJoin',
            swap: 'swap'
        };
        self.$scope.tableToModify = null;

        self.$scope.savedSearchName = {};
        self.$scope.savedSearchCategory = {};

        self.$scope.reportCategories = ReportCategories;

        self.$scope.roles       = this._commonHelper.getRolesArray();
        self.$scope.is_admin    = self._commonHelper.checkifAdmin(self.$scope.roles);
        self.$scope.is_public   = {};
        self.$scope.Math        = Math;

        this._initializeSQLWizardData();

        self.$scope.alertData   = {};
        self.$scope.hostcontexts = {};
        self.$scope.excludedHosts = '';
        self.$scope.hostselectionstate = {};
        self.$scope.showEnvironmentFilterButtons = false;

        $scope.showQuery = false;

        //load report - priority - latest data from
        if (!self._commonHelper._isObjEmpty(self._wizardSharedService.restoreScopeState()))
        {

            self.$scope.SQL = self._wizardSharedService.restoreScopeState();
            var tmpReport =  self._wizardSharedService.restoreReportProperties();

            if (!self._commonHelper._isObjEmpty(tmpReport))
            {
                self.$scope.reportLabel     = tmpReport.reportLabel;
                self.$scope.savedSearchName.input = self.$scope.reportLabel; // for modal window
                self.$scope.savedSearchCategory.input = tmpReport.reportCategory || '';

                self.$scope.reportId    = tmpReport.reportId;
                self.$scope.reportRoles = tmpReport.reportRoles;

                self.$scope.is_own      = tmpReport.is_own;
                self.$scope.can_edit    = tmpReport.can_edit;
                self.$scope.can_delete  = tmpReport.can_delete;
                self.$scope.readonly    = tmpReport.readonly;
                self.$scope.is_public   = {};
                self.$scope.is_public.input = Boolean(tmpReport.is_public);
                self.$scope.noResultsSuccess = tmpReport.noResultsSuccess;
            }

            self._restoreScopes();
            self._refreshDropdowns();

            self._commonHelper.setContextVariables(self.$scope, self.$scope.SQL);

            $scope.savedSearchName.input  = self.$scope.reportLabel;
        }
        else
        {
            if ($routeParams.reportid !== undefined)
            {
                self._reportService.loadReport($routeParams.reportid).then(
                    function(result) {
                        var data = result.data;
                        var formData = angular.fromJson(data['AdvancedReportsData']);
                        if (formData.SQL !== undefined)
                        {
                            $scope.SQL = angular.fromJson(formData.SQL);
                            self._wizardSharedService.scopeStateChanged(self.$scope.SQL)
                        }
                        if (formData.noResultsSuccess){
                            $scope.noResultsSuccess = formData.noResultsSuccess === "true";
                        }
                        self._restoreScopes();
                        self._refreshDropdowns();
                        self._commonHelper.setContextVariables(self.$scope, self.$scope.SQL);


                        $scope.reportLabel       = data.label;
                        $scope.reportId          = $routeParams.reportid;
                        $scope.savedSearchName.input = data.label;

                        $scope.reportCategory       = (data.reportCategory !== undefined ? data.reportCategory : '');
                        $scope.savedSearchCategory.input = (data.reportCategory !== undefined ? data.reportCategory : '');

                        $scope.can_edit          = data.can_edit;
                        $scope.can_delete        = data.can_delete;
                        $scope.is_own            = data.is_own;
                        $scope.readonly          = data.readonly;
                        $scope.is_public = {};
                        $scope.is_public.input   = Boolean(data.is_public);
                        $scope.loadedSearch      = true;
                        $scope.reportRolesTMP    = (data.sharedPermission  !== undefined ? angular.fromJson(data.sharedPermission)  : {});
                        angular.forEach($scope.reportRolesTMP, function(key, value){
                           $scope.reportRoles[key] = true;
                        });


                        self._wizardSharedService.reportPropertiesChanged(self._commonHelper.getReportData(self.$scope));

                    },
                    function(error) {
                        var error = self._notificationService.createObjectForNotification('error', 500, 'Unable to load report');
                        self._notificationService.setNotification(error.type, error.data)
                    });
            } else if (sessionStorage.getItem('sql')) {
                self.$scope.SQL = JSON.parse(sessionStorage.getItem('sql'));
                self._restoreScopes();
                self._refreshDropdowns();
                self._commonHelper.setContextVariables(self.$scope, self.$scope.SQL);
            }
        }
    },

    defineScope: function() {
        this.$scope.instance = "editController";

        this.$scope.showTableFields      = this.showTableFields.bind(this);
        this.$scope.updateSelectedTable  = this.updateSelectedTable.bind(this);
        this.$scope.applyTableSelecting  = this.applyTableSelecting.bind(this);
        this.$scope.convertTableToMain   = this.convertTableToMain.bind(this);
        this.$scope.modifyJoinType       = this.modifyJoinType.bind(this);
        this.$scope.fieldsToArray        = this.fieldsToArray.bind(this);
        this.$scope.saveField            = this.saveField.bind(this);
        this.$scope.updateSelectedFields = this.updateSelectedFields.bind(this);
        this.$scope.splice               = this.splice.bind(this);

        this.$scope.clearAllFields       = this.clearAllFields.bind(this);
        this.$scope.updateLimit          = this.updateLimit.bind(this);

        this.$scope.runQuery             = this.runQuery.bind(this);
        this.$scope.saveReport           = this.saveReport.bind(this);
        this.$scope.deleteReport         = this.deleteReport.bind(this);

        this.$scope.showMeQuery          = this.showMeQuery.bind(this);

        //helper fnc
        this.$scope.isObjEmpty           = this.checkIfObjEmpty.bind(this);

        this.$scope.changeScopeState     = this.changeScopeState.bind(this);

        this.$scope.roles_disablePublicReport = this.roles_disablePublicReport.bind(this);
        this.$scope.publicReport_disableRoles = this.publicReport_disableRoles.bind(this);

        this.$scope.scrollToResult = this.scrollToResult.bind(this);
    },


    defineListeners: function() {
        var self = this;

        self.$scope.$on("hostContextApply_Event", function(event, hostContextObj) {
            self.$scope.SQL.hostcontexts          = angular.copy(hostContextObj.hostcontexts);
            self.$scope.hostcontexts              = self.$scope.SQL.hostcontexts;
            self.$scope.SQL.hostcontextsprofileid = angular.copy(hostContextObj.hostcontextsprofileid);
            self.$scope.SQL.hostcontextspath      = angular.copy(hostContextObj.hostcontextspath);
            self.$scope.alertData.hostContexts    = self.$scope.SQL.hostcontexts;
            self._wizardSharedService.reportPropertiesChanged(self._commonHelper.getReportData(self.$scope));
            self.$scope.showFilter = false;
        });

        self.$scope.$on('environmentExcludeChanged_Event', function(event, excludedHosts) {

            if (Object.keys(excludedHosts).length)
            {
                self.$scope.alertData.excludedHosts = {name: Object.values(excludedHosts).join(', '), excludes: Object.keys(excludedHosts)};
                self.$scope.SQL.excludedHosts = {name: Object.values(excludedHosts).join(', '), excludes: Object.keys(excludedHosts)};
                self.$scope.excludedHosts = {name: Object.values(excludedHosts).join(', '), excludes: Object.keys(excludedHosts)};
            }
            else {
                self.$scope.alertData.excludedHosts = '';
                self.$scope.excludedHosts = '';
                self.$scope.SQL.excludedHosts = '';
            }

        });

        self.$scope.$watch('SelectedDCA', function (newValue) {
            // if SelectedDCA element has removed
            if (Object.keys(newValue).length < self.$scope.SelectedTablesCount) {
                // find removed key
                Object.keys(self.$scope.SelectedTables).forEach(function (index) {
                    if (!newValue.hasOwnProperty(index)) {
                        self.removeTableFields(index);
                    }
                })
            }

            self.showTableFields();
            self._event_scopeStateChanged();
            self.$scope.SelectedTablesCount = Object.keys(newValue).length;
        }, true);
    },
// -------------- View functions -------------
    /*
     * When user click on "table" checkboxes
     */
    showTableFields: function () {
        let self = this;
        let $scope = self.$scope;

        angular.forEach($scope.SelectedDCA, function (element, tableName) {
                // if table does not exist in SelectedDCA - add it, and unset all fields
                if (!$scope.SelectedDCA[tableName].hasOwnProperty('Fields')) {
                    $scope.SelectedDCA[tableName] = DCA_TABLES[tableName];

                    $scope.SelectedDCA[tableName].joinType = element.joinType;
                    angular.forEach($scope.SelectedDCA[tableName]['Fields'], function (field, fieldId) {
                        $scope.SelectedDCA[tableName]['Fields'][fieldId]['isSelected'] ??= false;
                    });
                }
            $scope.SQL.tables[tableName] = element.joinType;
        });
    },

    removeTableFields: function(tableName) {
        let $scope = this.$scope;
        if ($scope.SQL !== undefined && !_.isEmpty($scope.SQL)) {
            angular.forEach($scope.SQL, function (sqlPart, key) {
                switch (key) {
                    case "fields":
                    case "orderby":
                    case "groupby":
                        angular.forEach(sqlPart, function (data, item) {
                            if (data.table == tableName) {
                                delete ($scope.SQL[key][item]);
                            }
                        });
                        break;

                    case "filters": // this is array, so we have to use different way of deleting
                        angular.forEach(sqlPart, function (data, item) {
                            if (data.table === tableName) {
                                $scope.SQL[key].splice(item, 1);
                            }
                        });
                        break;
                    case "tables":
                        if ($scope.SQL.tables[tableName] !== undefined) {
                            delete $scope.SQL.tables[tableName];
                        }
                        break;
                }
            });
        }
        delete ($scope.SelectedDCA[tableName]);
        this._event_scopeStateChanged();
        this._refreshDropdowns();
    },

    updateSelectedTable: function (tableID, event) {
        let checkBoxState = event.target.checked;
        let $scope = this.$scope;
        // if table selected
        if (checkBoxState == true) {
            $scope.currentTableID = tableID;
            $scope.modalData.joinType = $scope.SelectedTablesCount == 0 ? $scope.joinTypes.main : $scope.joinTypes.left;
            $scope.modalWindow.open('selectTable', $scope);
            event.target.checked = false;
        } else { // if a table has deselected
            // if the main table has deselected then we need to re-assign the main table to another one
            if ($scope.SelectedDCA[tableID].joinType == $scope.joinTypes.main) {
                switch ($scope.SelectedTablesCount) {
                    case 1:
                        // if only main table has selected then deselected: just remove it
                        delete $scope.SelectedDCA[tableID];
                        break;
                    case 2:
                        // if only 2 tables have selected and deselected main one then make second table as main
                        Object.keys($scope.SelectedDCA).forEach(function (index) {
                            if (tableID !== index) {
                                $scope.SelectedDCA[index].joinType = $scope.joinTypes.main;
                            }
                        })
                        delete $scope.SelectedDCA[tableID];
                        break;
                    default:
                        // in case of more then 2 tables have selected and deselected main one, use should select manually new main table
                        event.target.checked = true;
                        $scope.modalWindow.open('selectMainTable', $scope);
                        $scope.tableToDelete = tableID;
                        break;
                }
            } else {
                delete $scope.SelectedDCA[tableID];
            }
        }

    },

    modifyJoinType: function (tableID) {
        this.$scope.currentTableID = tableID;
        this.$scope.modalWindow.open('selectTable', this.$scope);
        this.$scope.modalData.joinType = null;
        if (this.$scope.SelectedDCA[tableID].joinType !== this.$scope.joinTypes.main) {
            this.$scope.modalData.joinType = this.$scope.SelectedDCA[tableID].joinType;
        }
    },

    fieldsToArray: function (obj) {
        let arr = [];
        Object.keys(obj).forEach((v) => {
            let copiedObject = obj[v];
            copiedObject['fieldId'] = v;
            arr.push(copiedObject)
        })
        return arr;
    },

    applyTableSelecting: function () {
        let self = this;

        self.$scope.SelectedTables[self.$scope.currentTableID] = true;
        if (self.$scope.SelectedTablesCount != 0 && self.$scope.modalData.joinType == self.$scope.joinTypes.swap) {
            self.$scope.modalData.joinType = self.$scope.joinTypes.main;
            Object.keys(self.$scope.SelectedDCA).forEach(function (key) {
                if (self.$scope.SelectedDCA[key].joinType == self.$scope.joinTypes.main) {
                    self.$scope.SelectedDCA[key].joinType = self.$scope.joinTypes.left;
                }
            })
        }

        // if main table has changed join type
        if (
            this.$scope.SelectedDCA.hasOwnProperty(self.$scope.currentTableID) &&
            this.$scope.SelectedDCA[self.$scope.currentTableID].joinType == self.$scope.joinTypes.main
        ) {
            this.$scope.tableToModify = {tableID: self.$scope.currentTableID, joinType: self.$scope.modalData.joinType}
            this.$scope.modalWindow.open('selectMainTable', this.$scope);
        } else {
            self.$scope.SelectedDCA[self.$scope.currentTableID] = {joinType: self.$scope.modalData.joinType};
        }
    },

    convertTableToMain: function () {
        this.$scope.SelectedDCA[this.$scope.modalData.newMainTableId].joinType = this.$scope.joinTypes.main;
        if (this.$scope.tableToDelete != null) {
            $('#table_' + this.$scope.tableToDelete).prop('checked', false);
            delete this.$scope.SelectedDCA[this.$scope.tableToDelete];
            this.$scope.tableToDelete = null;
        }

        if (this.$scope.tableToModify != null) {
            this.$scope.SelectedDCA[this.$scope.tableToModify.tableID].joinType = this.$scope.tableToModify.joinType;
            this.$scope.tableToModify = null;
        }
    },

    /*
     * When user clicks on public report checkbox
     */
    publicReport_disableRoles: function() {
        var self = this;
        var $scope = self.$scope;
        self._commonHelper.publicReport_disableRoles($scope.is_public.input, $scope);
    },
    // when user clicks on roles
    roles_disablePublicReport: function() {
        var self = this;
        var $scope = self.$scope;
        self._commonHelper.roles_disablePublicReport($scope.is_public.input, $scope);
    },
    /*
     * Delete item from SQL fields, filters orderby and groupby scopes
     */
    splice: function(field, currentScope) {
        var self = this;
        var $scope = self.$scope;

        switch(currentScope) {
            case 'fields':
                delete $scope.SQL.fields[field.sqlField]; //because fields scope is a object
                self._removeRelatedFields_OnSelectFieldDeleted(field);
                break;

            case 'filters':
                $scope.SQL[currentScope].splice($.inArray(field, $scope.SQL[currentScope]), 1);
                break;

            default: //orderby and groupby
                delete $scope.SQL[currentScope][field.sqlField]; //because that scopes are objects
        }

        self._event_scopeStateChanged();
        self._refreshDropdowns();
    },

    /*
     * When user select/deselect table - refresh related fields
     */
    updateSelectedFields: function (tableId,  fieldId)
    {
        var self = this;
        var $scope = self.$scope;

        if ($scope.SelectedDCA[tableId]['Fields'][fieldId]['isSelected'] === true)
        {
             self.saveField ('fields', tableId, fieldId, null);
        }
        else
        {
            self.splice($scope.SelectedDCA[tableId]['Fields'][fieldId], 'fields');
        }
    },

    /*
     * When user select item in fields, filters orderby and groupby sections
     */
    saveField: function(scopeName, tableId,  fieldId, $event) {
        var self = this;
        var $scope = self.$scope;

        if ($event !== null && $event !== undefined)
        {
            $event.preventDefault();
        }
        $scope.selectedCriteria = {};

        if(scopeName === 'fields') {
            $scope.selectedCriteria = $scope.SelectedDCA[tableId]['Fields'][fieldId];
        }
        else {
            $scope.selectedCriteria = $scope.SelectedDCA[tableId]['Fields'][fieldId];
        }

        if ($scope.selectedCriteria.name === '' || $scope.selectedCriteria.name === null || $scope.selectedCriteria.name === undefined )
        {
            alert('Field not found. DCA corrupted');
            return;
        }

        var selectedField = {}; // store selected field

        // to break javascript link from DCA
        angular.copy($scope.selectedCriteria, selectedField);
        if (selectedField.name === undefined)
        {
            alert('Unable to find field by name. DCA corrupted');
            return;
        }
        // some default values
        switch(scopeName)
        {
            case 'fields':
                //ALIAS: check if field exist in fields scope, if no - add, if yes, create alias and update realated dropdowns
                if($scope.SQL.fields[selectedField['sqlField']] !== undefined )
                {
                    var originalSqlField = selectedField['sqlField']; // we can't use aliases in where, that's why we should use name of the original element
                    // so field is exist,
                    var newFieldName = fieldId + '_' + $scope.fieldIndex; // create alias

                    selectedField['label']      = originalSqlField.label;  // new field with alias
                    selectedField['name']       = newFieldName;  // new value equal to label
                    selectedField['sqlField']   = selectedField['sqlField'] + ' AS ' +  newFieldName;
                    selectedField['clonedFrom'] = originalSqlField;

                    $scope.fieldIndex ++;
                }

                // add new field to the selected scope (fields, filters ...  )
                $scope.SQL.fields[selectedField['sqlField']] = selectedField;
                break;

            case 'filters':
                //add some default values
                selectedField['logical']    = 'AND';
                selectedField['comparison'] = $scope.DefaultComparisions[selectedField.dataType];
                $scope.SQL[scopeName].push(selectedField);
                break;

            case 'groupby':
                $scope.SQL.groupby[selectedField['sqlField']] = selectedField;
                break;

            case 'orderby':
                selectedField['order'] = 'ASC';
                $scope.SQL.orderby[selectedField['sqlField']] = selectedField;
                break;
            default:
                return;
        }
        self._event_scopeStateChanged();   // broadcast scopechange event

        self._refreshDropdowns();  // refresh Filter, GroupBy, OrderBy
    },

    /*
     * When user click on clear all button
     */
    clearAllFields: function () {
        var self = this;
        sessionStorage.removeItem('sql');
        self._initializeSQLWizardData();

        self._event_scopeStateChanged();
        self._refreshDropdowns();
    },
    /*
     * When limit dropdown get changed
     */
    updateLimit: function() {
        var self = this;
        self._event_scopeStateChanged();
    },
    /*
     * Run query click - save SQL scope in sharedWizard and redirect to run action
     */
    runQuery: function() {
        var self = this;

        self._wizardSharedService.scopeStateChanged(self.$scope.SQL);
        self._wizardSharedService.reportPropertiesChanged(self._commonHelper.getReportData(self.$scope));
        self.$scope.SQL = self._wizardSharedService.restoreScopeState();

        // save to local storage for purpose of refreshing/clicking 'back' in browser
        sessionStorage.setItem('sql', JSON.stringify(self.$scope.SQL));
        sessionStorage.setItem('noResultSuccess', JSON.stringify(self.$scope.noResultsSuccess));
        var url = '/report/run';
        self.$location.path(url);
    },



// -------------- Initialization -----------------
    /*
     * Prepare all scopes
     */
    _initializeSQLWizardData: function() {
        var self = this;
        var $scope = self.$scope;
        $scope.dcaByTable = {};

        //self._commonHelper.prepareDCA(); disabled for now

        var copiedDCA     = self._commonHelper.convertDCA_TO_ARRAY(DCA_TABLES);
        $scope.dcaByTable = self._commonHelper.groupConvertedDCAbyTable(copiedDCA);

        $scope.SelectedTables = {}; // all tables which selected in Tables section
        $scope.SelectedDCA    = {}; // copy of DCA for only selected tables
        $scope.SelectedTablesCount = 0;
        $scope.joinType = {};

        $scope.GroupByOrderByDCA = {};
        $scope.groupByFieldsList = {};
        $scope.orderByFieldsList = {};

        $scope.spinner = '';

        $scope.loadedSearch = false; // set to true when load search
        $scope.reportLabel = '';

        $scope.Comparison  = Comparison;
        $scope.Logical     = Logical;
        $scope.Order       = Order;
        $scope.Limit       = Limit;

        $scope.noResultsSuccess = false;

        $scope.DefaultComparisions = DefaultComparisions;

        $scope.SQL = {};
        $scope.SQL.fields   = {}; // SELECT   fields  //// NOTE !!! this is OBJECT, this made to be sure that we will newer have 2 fields with the same name
        $scope.SQL.tables   = {}; // FROM tables

        $scope.SQL.filters  = []; // WHERE    filters

        $scope.SQL.groupby  = {}; // GROUP BY groupby
        $scope.SQL.orderby  = {}; // ORDER BY sort

        $scope.SQL.SQLSTRING = '';

        $scope.SQL.hostcontexts = {};

        $scope.fieldIndex = 1;  // just some unique index for alias fields
    },


// helpers
    /*
     * Refresh dropdows
     */
    _refreshDropdowns: function () {
        var self = this;
        var $scope = self.$scope;
        self._refreshGroupByOrderBy();
        // reset value in all dropdowns
        $scope.selectedCriteria = [];
    },


    /**
     * in the Group by and Order by we must use all fields from tables which present in select or filter
     *
     * We must skip fields from those tables if they already present in group or order list
     *
     */
    _refreshGroupByOrderBy: function () {
        var self = this;
        var $scope = self.$scope;

        var tables = {};
        //clear scopes
        $scope.GroupByOrderByDCA = {};
        $scope.groupByFieldsList = {};
        $scope.orderByFieldsList = {};

        // find unique tables FROM Select and Filter
        if ($scope.SQL.fields !== undefined)
        {
            angular.forEach($scope.SQL.fields, function(field, key){
                if(tables[field.table] === undefined) {
                    tables[field.table] = field.table;
                }
            });
        }

        if ($scope.SQL.filters !== undefined)
        {
            angular.forEach($scope.SQL.filters, function(field, key){
                if(tables[field.table] === undefined) {
                    tables[field.table] = field.table;
                }
            });
        }
        // if there is no data - exit
        if (self._commonHelper._isObjEmpty(tables))
        {
            return;
        }

        //copy DCA tables into GroupByOrderByDCA
        angular.forEach(tables, function(table, key){
            if ($scope.SelectedDCA[table] !== undefined)
            {
                $scope.GroupByOrderByDCA[table] = $scope.SelectedDCA[table];
            }
        });

        // this can help to solve backward compatibility issues
        //  - stuff won't break, but query could be invalid
        if (self._commonHelper._isObjEmpty($scope.GroupByOrderByDCA))
        {
            return;
        }

        // GroupBy: Copy DCA and delete fields which is already in SQL.groupBy - prevent dublicates
        $scope.groupByFieldsList = angular.copy($scope.GroupByOrderByDCA);

        angular.forEach($scope.groupByFieldsList, function(table, tableId){
            angular.forEach(table['Fields'], function(field, fieldId){
                // check if field already exists in groupby list, if so - delete
                if ($scope.SQL.groupby[fieldId] !== undefined) {
                    delete($scope.groupByFieldsList[tableId]['Fields'][fieldId]);
                }
            });
        });


        // OrderBy: Copy DCA and delete fields which is already in SQL.orderBy - prevent dublicates
        $scope.orderByFieldsList = angular.copy($scope.GroupByOrderByDCA);

        angular.forEach($scope.orderByFieldsList, function(table, tableId){
            angular.forEach(table['Fields'], function(field, fieldId){
                // check if field already exists in orderby list, if so - delete
                if ($scope.SQL.orderby[fieldId] !== undefined) {
                    delete($scope.orderByFieldsList[tableId]['Fields'][fieldId]);
                }
            });
        });
    },

// ------------------- Services --------------
    _event_scopeStateChanged: function() {
        var self = this;
        self._wizardSharedService.scopeStateChanged(self.$scope.SQL);
        self._sqlHelper.setSQLScope(self.$scope.SQL);
        self.$scope.SQL.SQLSTRING = self._sqlHelper.getSQL_FULL();
    },

// --- system Func
    _removeRelatedFields_OnSelectFieldDeleted: function(field) {
        var self = this;
        var $scope = self.$scope;

        var length = 0;
        var i = 0;

        length = $scope.SQL['filters'].length;
        for(i = length-1;  i >= 0; i--) {
            if($scope.SQL['filters'][i].sqlField === field.sqlField) {
                $scope.SQL['filters'].splice(i, 1);
            }
        }

        if($scope.SQL.orderby[field.sqlField] !== undefined) {
            delete $scope.SQL.orderby[field.sqlField];
        }

        if($scope.SQL.groupby[field.sqlField] !== undefined) {
            delete $scope.SQL.groupby[field.sqlField];
        }
    },

    _restoreScopes:function() {
        var self = this;
        var $scope = self.$scope;

        //clear scopes
        $scope.SelectedDCA     = {};
        $scope.SelectedTables  = {};


        angular.forEach($scope.SQL.fields, function(field, fieldId){
            var tableName = field.table;

            if ($scope.SelectedDCA[tableName] === undefined)
            {
                $scope.SelectedDCA[tableName] = {};
                $scope.SelectedDCA[tableName] = DCA_TABLES[tableName];
            }

            if ($scope.SelectedDCA[tableName]['Fields'][fieldId] != undefined) {
                // mark field as selected
                $scope.SelectedDCA[tableName]['Fields'][fieldId].isSelected = true;
            }
           });

        let isMainTableSet = false;

        if ($scope.SQL.hasOwnProperty('tables')) {
            Object.keys($scope.SQL.tables).forEach(function (tableID) {
                if ($scope.SelectedDCA[tableID] === undefined) {
                    $scope.SelectedDCA[tableID] = {joinType: $scope.SQL.tables[tableID]};
                } else {
                    $scope.SelectedDCA[tableID].joinType = $scope.SQL.tables[tableID];
                }
                $scope.SelectedTables[tableID] = true;
            });
        } else {
            // if SQL does not have tables property then loaded old report
            // old reports had only INNER JOIN
            $scope.SQL.tables = {};
            Object.keys($scope.SelectedDCA).forEach(function (tableID) {
                $scope.SelectedDCA[tableID].joinType = isMainTableSet == false ? $scope.joinTypes.main : $scope.joinTypes.inner;
                isMainTableSet = true;
                $scope.SelectedTables[tableID] = true;
            });
        }
    },

    saveReport: function (isOverwrite) {
        var self = this;
        self._commonHelper.saveReport(isOverwrite, self.$scope, 'edit');
    },

    deleteReport: function(id) {
        var self = this;
        var $scope = self.$scope;

        if (id !== '')
        {
           self._reportService.deleteReport(id).then(
            function(result) {
                self.clearAllFields();
                self._wizardSharedService.resetScope();
                self._notificationService.setNotification('success', result.data);
                self.$scope.modalWindow.close('deleteSearchModal');
                self.$location.path('/custom/new');
            },
            function(error) {
                self._notificationService.setNotification('error', error.data);
            });
        }
    },

    // scroll page to the result div, used for the buttons on top
    scrollToResult: function() {
        window.scrollTo(0, document.getElementById('resultScrollTo').offsetTop - 100);
    },

    showMeQuery: function()
    {
        var self = this;
        var $scope = self.$scope;
        $scope.showQuery = ($scope.showQuery === true ? false:true);
    },

    changeScopeState: function() {
        var self = this;
        self._event_scopeStateChanged();
    },
    checkIfObjEmpty: function (val)
    {
       var self = this;
       return self._commonHelper._isObjEmpty(val);
    }
});
editController.$inject = ['$scope','$location', '$routeParams',
                          'reportService', 'wizardSharedService', 'commonHelper',
                          'sqlHelper', 'notificationService', 'paginationService',
                          'modalWindowService', 'hubManagementService'];