/*-
 * ~~~~~~licensing~~~~~~
 * entaxy-management-plugin
 * ==========
 * Copyright (C) 2020 - 2021 EmDev LLC
 * ==========
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ~~~~~~/licensing~~~~~~
 */
var Entaxy;
(function (Entaxy) {
    Entaxy._module.component('entaxyConnectors', {
        template:
        `
          <h2>
            Connectors
          </h2>

          <pf-toolbar class="entaxy-connector-toolbar" config="$ctrl.toolbarConfig"></pf-toolbar>
          <pf-table-view config="$ctrl.tableConfig"
                          columns="$ctrl.tableColumns"
                          action-buttons="$ctrl.tableActionButtons"
                          page-config="$ctrl.pageConfig"
                          items="$ctrl.viewedConnectors">
          </pf-table-view>
        `,
        controller: EntaxyConnectorsController
    })
    .name;

    function EntaxyConnectorsController(workspace, $uibModal, operationsService, jolokiaService) {
        'ngInject';

        var ctrl = this;
        ctrl.workspace = workspace;
        var entaxyJmxDomain = localStorage['entaxyJmxDomain'] || "ru.entaxy.esb";

        let filterValues = Entaxy.getAllBundleStates();

        ctrl.tableConfig = {
            selectionMatchProp: 'name',
            showCheckboxes: false
        };

        ctrl.toolbarConfig = {
            filterConfig: {
                fields: [
                    {
                        id: 'name',
                        title: 'Name',
                        placeholder: 'Filter by Name...',
                        filterType: 'text'
                    },
                    {
                        id: 'status',
                        title: 'Status',
                        placeholder: 'Filter by Status...',
                        filterType: 'select', // actually text has it rights to be
                        filterValues: filterValues
                    }
                ],
                resultCount: ctrl.viewedConnectors ? ctrl.viewedConnectors.length : 0,
                appliedFilters: [],
                onFilterChange: filterChange
            },
            actionsConfig: {
                primaryActions: [
                    { name: 'Add connector', actionFn: () => ctrl.showAddConnectorModal() },
//                    { name: 'Show Modal', actionFn: () => ctrl.showModal() }
                ]
            },
            isTableView: true
        };

        ctrl.columnDefs = [
            { field: 'name', displayName: 'Connector Name' },
            { field: 'status', displayName: 'Status' }
        ];

        ctrl.tableColumns = [
            { header: 'Connector Name', itemField: 'name' },
            { header: 'Status', itemField: 'status' }
        ];

        ctrl.tableActionButtons = [
            { name: 'Start', title: 'Start Connector', actionFn: startConnector },
            { name: 'Stop', title: 'Stop Connector', actionFn: stopConnector },
//            { name: 'Edit', title: 'Edit Connector', actionFn: editConnector },
            { name: 'Remove', title: 'Remove Connector', actionFn: removeConnector }
        ];

        ctrl.pageConfig = {
            pageNumber: 1,
            pageSize: 10,
            pageSizeIncrements: [5, 10, 20, 50, 100]
        };

        function filterChange(filters) {
            applyFilters(filters);
            ctrl.toolbarConfig.filterConfig.resultsCount = ctrl.viewedConnectors.length;
        };

        function applyFilters(filters) {
            ctrl.viewedConnectors = [];
            if (filters && filters.length > 0) {
                ctrl.connectors.forEach(function (connector) {
                    if (matchesFilters(connector, filters)) {
                        ctrl.viewedConnectors.push(connector);
                    }
                });
            } else {
                ctrl.viewedConnectors = ctrl.connectors;
            }
        };

        function matchesFilters(item, filters) {
            var matches = true;
            filters.forEach(function(filter) {
                if (!matchesFilter(item, filter)) {
                    matches = false;
                    return false;
                }
            });
            return matches;
        };

        function matchesFilter(item, filter) {
            var match = true;
            if (filter.id === 'name') {
                match = item.name.match(filter.value) !== null;
            } else if (filter.id === 'status') {
                match = item.status === filter.value;
            }
            return match;
        };

        ctrl.connectors = [];
        ctrl.viewedConnectors = [];

        ctrl.$onInit = function() {
            populateTable();
        }

        function populateTable() {
            ctrl.folderName = 'Коннекторы';
            ctrl.statusName = 'BundleState';

            let connectors = [];
            let count = 0; // FIXME CRUTCH

            let connectorsFolder = workspace.getSelectedMBean().get(ctrl.folderName);
            if (connectorsFolder) {
                connectorsFolder.children.forEach((child) => {
                    jolokiaService.getAttributes(child.objectName, [ctrl.statusName])
                    .then((response) => {
                        connectors.push({name: child.title, status: response[ctrl.statusName], mbeanName: child.objectName});
                    });
                    count++; // FIXME CRUTCH
                });

                ctrl.connectors = connectors;
                ctrl.viewedConnectors = connectors;
                ctrl.toolbarConfig.filterConfig.resultsCount = count; // FIXME CRUTCH
            }
        }

        ctrl.showAddConnectorModal = function() {
            $uibModal.open({
                component: 'entaxyAddConnectorModal',
                resolve: {
                    connector: null
                },
                size: 'lg',
                backdrop: 'static'
            })
            .result.then(connectorArgs => {
                addConnector(connectorArgs);
            });
        }

        ctrl.templates = Entaxy.getConnectorTemplates();

        ctrl.showModal = function() {
            $uibModal.open({
                component: 'entaxyModal',
                resolve: {
                    modalTitle: () => 'Add Connector',
                    firstStepTitle: () => 'Choose connector template',
                    secondStepTitle: () => 'Fill in connector template parameters',
//                    profile: null,
//                    profileNames: () => ctrl.profiles.map(profile => profile.name),
//                    profileIds: () => ctrl.profiles.map(profile => profile.id)
                    templates: () => ctrl.templates.map(template => { return { name: template }})
                },
                size: 'lg',
                backdrop: 'static'
           })
           .result.then(args => {
//                addConnector(args);
           });
       }

        function addConnector(connectorArgs) {

            let args = [];
            args.push(connectorArgs.connectorTemplateName);
            let argParams = '{';
            _.forEach(connectorArgs.connectorFields, (field) => {
                argParams += '\"' + field.label + '\":\"' + field.value + '\",';
            });
            if (argParams.length > 1) {
                argParams = argParams.substring(0, argParams.length - 1);
            }
            argParams += '}';
            args.push(argParams);

            let mbeanName = ctrl.workspace.getSelectedMBeanName();

            operationsService.executeOperation(mbeanName, { name: 'addConnector' }, args)
            .then(result => {
//                // FIXME FIXME FIXME FIXME FIXME FIXME
                setTimeout(() => populateTable(), 5000);

                ctrl.viewedConnectors = ctrl.connectors;
                ctrl.toolbarConfig.filterConfig.appliedFilters = [];
                ctrl.toolbarConfig.filterConfig.resultsCount = ctrl.viewedConnectors.length;

                Core.notification('success', result, 3000);
            }).catch(error => {
                Core.notification('danger', error, 5000);
            });
        }

        function startConnector(action, connector) {
            let mbeanName = workspace.getSelectedMBeanName();
            operationsService.executeOperation(mbeanName, { name: 'startConnector' }, [ connector.name ])
                .then(result => {
                    // FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
                    setTimeout(() => populateTable(), 100);

                    Core.notification('success', result, 3000);
                }).catch(error => {
                    Core.notification('danger', error, 5000);
                });
        }

        function stopConnector(action, connector) {
            let mbeanName = workspace.getSelectedMBeanName();
            operationsService.executeOperation(mbeanName, { name: 'stopConnector' }, [ connector.name ])
                .then(result => {
                    // FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
                    setTimeout(() => populateTable(), 100);

                    Core.notification('success', result, 3000);
                }).catch(error => {
                    Core.notification('danger', error, 5000);
                });
        }

        function removeConnector(action, connector) {
            let mbeanName = workspace.getSelectedMBeanName();
            operationsService.executeOperation(mbeanName, { name: 'removeConnector' }, [ connector.name ])
            .then(result => {
                ctrl.connectors.splice(ctrl.connectors.indexOf(connector), 1);
                ctrl.viewedConnectors = ctrl.connectors;
                ctrl.toolbarConfig.filterConfig.appliedFilters = [];
                ctrl.toolbarConfig.filterConfig.resultsCount = ctrl.viewedConnectors.length;

                Core.notification('success', result, 3000);
            }).catch(error => {
                Core.notification('danger', error, 5000);
            });
        }

        ctrl.dismissAlert = () => ctrl.alert = null;

    }
    EntaxyConnectorsController.$inject = ['workspace', '$uibModal', 'operationsService', 'jolokiaService'];

})(Entaxy || (Entaxy = {}));