/*-
 * ~~~~~~licensing~~~~~~
 * entaxy-management-plugin
 * ==========
 * Copyright (C) 2020 - 2025 EmDev LLC
 * ==========
 * You may not use this file except in accordance with the License Terms of the Copyright
 * Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
 * rights to the Software and any copies are the property of the Copyright Holder. Unless
 * it is explicitly allowed the Copyright Holder, the User is prohibited from using the
 * Software for commercial purposes to provide services to third parties.
 * 
 * The Copyright Holder hereby declares that the Software is provided on an "AS IS".
 * Under no circumstances does the Copyright Holder guarantee or promise that the
 * Software provided by him will be suitable or not suitable for the specific purposes
 * of the User, that the Software will meet all commercial and personal subjective
 * expectations of the User, that the Software will work properly, without technical
 * errors, quickly and uninterruptedly.
 * 
 * Under no circumstances shall the Copyright Holder or its Affiliates is not liable
 * to the User for any direct or indirect losses of the User, his expenses or actual
 * damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
 * or damage to data, property, etc.
 * ~~~~~~/licensing~~~~~~
 */
var Entaxy;
(function (Entaxy) {
    Entaxy._module.component('testModal', {
        bindings: {
            modalInstance: '<',
            resolve: '<'
        },
        template:
        `
        <div style="vertical-align: middle">
            <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">{{$ctrl.modalTitle}}</h4>
            </div>
            <div class="modal-list-container" ng-if="$ctrl.step1">
              <div class="modal-body" style="height:203px; max-height:203px">
                <div class="col-md-auto">
                  <h2>{{$ctrl.firstStepTitle}}</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-if="$ctrl.step2" ng-submit="$ctrl.save($ctrl.formFields)">
              <div class="modal-body" style="height:115px; max-height:115px">
                <div class="col-md-auto">
                  <h2>{{$ctrl.secondStepTitle}}</h2>
                </div>
                <hr class="col-md-auto">
              </div>
              <div class="modal-body" style="height:388px; max-height:388px">
                <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-7">
                    <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>
                    <button type="button" class="btn btn-link btn-add-modal" ng-click="$ctrl.addModal(formField)"
                        ng-if="formField.hasAddButton && !formField.nestedValue">
                      <span class="pficon pficon-add-circle-o"></span>
                    </button>
                    <button type="button" class="btn btn-link btn-add-modal" ng-click="$ctrl.deleteNestedValue(formField)"
                        ng-if="formField.hasAddButton && formField.nestedValue">
                      <!--<span class="pficon pficon-error-circle-o"></span>-->
                      <span class="pficon pficon-delete"></span>
                    </button>
                  </div>
                </div>
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-default" ng-if="$ctrl.hasSteps" ng-click="$ctrl.back()">Back</button>
                <button type="submit" class="btn btn-primary">Add</button>
              </div>
            </form>
        </div>
        `,
        controller: testModalController
    })
    .name;

    function testModalController(workspace, $uibModal) {
        'ngInject';

        var ctrl = this;

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

        ctrl.$onInit = function() {
            Entaxy.log.info('MODAL!!!');

            ctrl.modalTitle = ctrl.resolve.modalTitle ? ctrl.resolve.modalTitle : 'Test Modal'; // fixme do required
            ctrl.firstStepTitle = ctrl.resolve.firstStepTitle ? ctrl.resolve.firstStepTitle : ctrl.modalTitle;
            ctrl.secondStepTitle = ctrl.resolve.secondStepTitle ? ctrl.resolve.secondStepTitle : ctrl.modalTitle;

            ctrl.templates = ctrl.resolve.templates ? ctrl.resolve.templates : null;

            if (ctrl.templates && ctrl.templates.length !== 0) {
                if (ctrl.templates.length > 1) {
                    ctrl.step1 = true;
                    ctrl.step2 = false;
                    ctrl.hasSteps = true;

                    ctrl.viewedTemplates = ctrl.templates;
                    ctrl.toolbarConfig.filterConfig.resultsCount = ctrl.viewedTemplates.length;
                } else if (ctrl.templates.length === 1) {
                    ctrl.step1 = false;
                    ctrl.step2 = true;
                    ctrl.hasSteps = false;

                    ctrl.formFields = ctrl.resolve.formFields ? ctrl.resolve.formFields : null; // fixme

                    ctrl.formFields.unshift({
                        label: 'factoryId',
                        type: 'java.lang.String',
                        helpText: null,
                        value: ctrl.templates[0].name,
                        isReadOnly: true
                    });
                }
            } else {
                ctrl.cancel('Templates are not found');
            }
        }

        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: {},
        };

        ctrl.listConfig = {
            selectionMatchProp: 'name',
            selectItems: true,
            showSelectBox: false
        }

        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;

            if (!ctrl.formFields || ctrl.listConfig.selectedItems[0].name !== ctrl.formFields[0].value) {
                ctrl.formFields = Entaxy.getConnectorTemplateParams(ctrl.listConfig.selectedItems[0].name); // todo mb set values to null through map
                ctrl.formFields.unshift({
                    label: 'factoryId',
                    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.cancel = function(reason) {
            ctrl.modalInstance.dismiss(reason);
        }

        function getChildModalFormFields(formField) {
            // todo somehow use current formField to get childFormFields from server

            let newFormFields = [];
            for (var i = 0; i < 3; i++) {
                newFormFields.push({
                    label: 'field' + i,
                    value: '',
                    type: Entaxy.convertToHtmlInputType('entaxy.runtime.profile')
                });
            }
            newFormFields.push({
                label: 'field3',
                value: '',
                type: Entaxy.convertToHtmlInputType('entaxy.runtime.profile'),
                hasAddButton: true
            });
            return newFormFields;
        }

        ctrl.addModal = function(formField) {

            let newFormFields = getChildModalFormFields();

            $uibModal.open({
                component: 'testModal',
                resolve: {
                    modalTitle: () => 'Test Child Modal',
                    templates: () => [ { name: 'testChild' } ],
                    formFields: () => newFormFields
                },
                size: 'lg',
                backdrop: 'static',
                windowTopClass: 'modal-top-margin-override'
            })
            .result.then(args => {
                _.forEach(args.fields, (field) => {
                    if (field.label === 'field0') { // fixme it may be id or name
                        formField.value = field.value;
                    }
                });
                formField.nestedValue = args;
            });
        }

        ctrl.deleteNestedValue = function(formField) {
            formField.nestedValue = null;
            formField.value = null;
        }

        ctrl.save = function(item) {
            ctrl.errors = validateFields(item);

            if (Object.keys(ctrl.errors).length === 0) {
                let factoryIdName = ctrl.formFields.shift().value;

                let args = {
                    factoryId: ctrl.templates.find((template) => template.name === factoryIdName),
                    fields: ctrl.formFields.map(formField => { return { label: formField.label, value: (formField.nestedValue ? formField.nestedValue : formField.value) }; })
                };

                ctrl.modalInstance.close(args);
            }
        }

        function validateFields(item) {
            let errors = {};
            // todo validation
            return errors;
        }
    }
    testModalController.$inject = ['workspace', '$uibModal'];

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