/*-
 * ~~~~~~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('entaxyAddConnectorModal', {
        bindings: {
            modalInstance: '<',
            resolve: '<'
        },
        template:
        `
          <div class="modal-header">
            <button type="button" class="close" aria-label="Close" ng-click="$ctrl.cancel()">
              <span class="pficon pficon-close" aria-hidden="true"></span>
            </button>
            <h4 class="modal-title">Add Connector</h4>
          </div>
          <div class="modal-list-container" ng-show="$ctrl.step1">
            <div class="modal-body" style="height:203px; max-height:203px">
              <div class="col-md-auto">
                <h2>Choose connector template</h2>
              </div>
              <hr class="col-md-auto">
              <div class="col-md-12">
                <pf-toolbar class="entaxy-template-toolbar" config="$ctrl.toolbarConfig"></pf-toolbar>
              </div>
            </div>
            <div class="modal-body" style="height:300px; max-height:300px">
              <pf-list-view class="entaxy-template-list" items="$ctrl.viewedTemplates" config="$ctrl.listConfig">
                <div class="list-view-pf-description">
                  <div class="list-group-item-heading">
                    {{item.name}}
                  </div>
                </div>
              </pf-list-view>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-default" ng-click="$ctrl.next()"
                  ng-disabled="$ctrl.listConfig.selectedItems.length === 0">Next</button>
            </div>
          </div>
          <form name="connectorForm" class="form-horizontal" ng-show="$ctrl.step2" ng-submit="$ctrl.saveConnector($ctrl.formFields)">
            <div class="modal-body" style="height:503px; max-height:503px">
              <div class="col-md-auto">
                <h2>Fill in connector template parameters</h2>
              </div>
              <hr class="col-md-auto">
              <div class="form-group" ng-repeat="formField in $ctrl.formFields">
                <label class="col-sm-3 control-label" ng-class="{'required-pf': formField.isRequired}" for="{{formField.label}}">{{formField.label}}</label>
                <div class="col-sm-8">
                  <input type="{{formField.type}}" id="{{formField.label}}" ng-class="{'form-control': formField.type !== 'checkbox'}"
                        ng-model="formField.value" ng-readonly="formField.isReadOnly">
                  <!--<span class="help-block">{{formField.helpText}}</span>-->
                </div>
              </div>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-default" ng-click="$ctrl.back()">Back</button>
              <button type="submit" class="btn btn-primary">Add</button>
            </div>
          </form>
        `,
        controller: EntaxyAddConnectorModalController
    })
    .name;

    function EntaxyAddConnectorModalController(workspace) {
        'ngInject';

        var ctrl = this;

//        ctrl.errors = null;

        Entaxy.log.info('MODAL???');

        ctrl.$onInit = function() {
            Entaxy.log.info('MODAL!!!');
            ctrl.connector = ctrl.resolve.connector ? ctrl.resolve.connector : null; // FIXME
            ctrl.step1 = true;
            ctrl.step2 = false;
//            ctrl.formFields = ctrl.resolve.args.map(arg => {
//                let formField = {
//                    label: arg.name,
//                    type: Entaxy.convertToHtmlInputType(arg.type)
//                };
//                return formField;
//            });
//            Entaxy.log.info('FORM FIELDS ' + JSON.stringify(ctrl.formFields));
            let templates = Entaxy.getConnectorTemplates();
            ctrl.templates = templates.map(template => { return { name: template }});
//            Entaxy.log.info('TEMPLATES ' + JSON.stringify(templates));
//            Entaxy.log.info('TEMPLATES ' + JSON.stringify(ctrl.templates));
            ctrl.viewedTemplates = ctrl.templates;
            ctrl.toolbarConfig.filterConfig.resultsCount = ctrl.viewedTemplates.length;
        }

        ctrl.toolbarConfig = {
            filterConfig: {
                fields: [
                    {
                        id: 'name',
                        title: 'Name',
                        placeholder: 'Filter by Name...',
                        filterType: 'text'
                    }
                ],
                resultCount: ctrl.viewedTemplates ? ctrl.viewedTemplates.length : 0,
                appliedFilters: [],
                onFilterChange: filterChange
            },
            actionsConfig: {},
//            isTableView: true
        };

        ctrl.listConfig = {
            selectionMatchProp: 'name',
            selectItems: true,
//            selectedItems: [],
            showSelectBox: false,
            dlbClick: true,
            onDblClick: function(item, event){
            	ctrl.listConfig.selectedItems.push(item);
            	ctrl.next();
            }
        }

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

        function applyFilters(filters) {
            ctrl.viewedTemplates = [];
            if (filters && filters.length > 0) {
                ctrl.templates.forEach(function (template) {
                    if (matchesFilters(template, filters)) {
                        ctrl.viewedTemplates.push(template);
                    }
                });
            } else {
                ctrl.viewedTemplates = ctrl.templates;
            }
        };

        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;
            }
            return match;
        };

        ctrl.next = function() {
            ctrl.step1 = false;
            ctrl.step2 = true;

            Entaxy.log.info('Selected item ' + JSON.stringify(ctrl.listConfig.selectedItems));

            if (!ctrl.formFields || ctrl.listConfig.selectedItems[0].name !== ctrl.formFields[0].value) {
                ctrl.formFields = Entaxy.getConnectorTemplateParams(ctrl.listConfig.selectedItems[0].name); //ctrl.listConfig.selectedItems[0]
                ctrl.formFields.unshift({
                    label: 'templateName',
                    type: 'java.lang.String',
                    helpText: null,
                    value: ctrl.listConfig.selectedItems[0].name,
                    isReadOnly: true
                });
                ctrl.formFields.forEach(formField => formField.type = Entaxy.convertToHtmlInputType(formField.type));
            }
        }

        ctrl.back = function() {
            ctrl.step1 = true;
            ctrl.step2 = false;

//            ctrl.formFields = null;
        }

        ctrl.cancel = function() {
            Entaxy.log.info('QUIT MODAL');
            ctrl.modalInstance.dismiss();
        }
//
        ctrl.saveConnector = function(connector) { // FIXME
            Entaxy.log.info('SAVE CONNECTOR: ' + JSON.stringify(connector));
            ctrl.errors = validateFields(connector); // FIXME
            Entaxy.log.info('ERRORS ' + JSON.stringify(ctrl.errors));

            if (Object.keys(ctrl.errors).length === 0) {
                // TODO
                let connectorArgs = {
                    connectorTemplateName: ctrl.formFields.shift().value,
                    connectorFields: ctrl.formFields.map(formField => { return { label: formField.label, value: formField.value }; })
                };

                ctrl.modalInstance.close(connectorArgs);
            }
        }

        function validateFields(connector) {
            Entaxy.log.info('VALIDATION START');
            let errors = {};

            Entaxy.log.info('VALIDATION END');
            return errors;
        }
    }
    EntaxyAddConnectorModalController.$inject = ['workspace'];

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