/*-
 * ~~~~~~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('testModal2', {
        bindings: {
            modalInstance: '<',
            resolve: '<'
        },
        template:
        `
          <div style="entaxy-modal-container">
            <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 ng-if="$ctrl.step1">
              <div class="modal-body-header" style="height:70px; max-height:70px; margin-bottom:15px; padding-top: 5px; padding-left: 15px; padding-right: 15px; border-bottom: 1px #f5f5f5 solid;">
                <h2>{{$ctrl.firstStepTitle}}</h2>
              </div>
              <div class="entaxy-modal-body" style="max-height: calc(100vh - 200px); overflow-y: auto; padding: 0px">
                <first-step-modal-test templates="$ctrl.templates" selected="$ctrl.selectedItem" change-selection="$ctrl.changeSelection"></first-step-modal-test>
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-default" ng-click="$ctrl.next()"
                      ng-disabled="!$ctrl.selectedItem">Next</button>
              </div>
            </div>

            <div ng-if="$ctrl.step2">
              <div class="modal-body-header" style="height:70px; max-height:70px; margin-bottom:15px; padding-top: 5px; padding-left: 15px; padding-right: 15px; border-bottom: 1px #f5f5f5 solid;">
                <h2>{{$ctrl.secondStepTitle}}</h2>
              </div>
              <div class="entaxy-modal-body" style="max-height: calc(100vh - 200px); overflow-y: auto; padding: 0px">
                <second-step-modal-test groups="$ctrl.groups" fields="$ctrl.formFields" errors="$ctrl.errors"></second-step-modal-test>
              </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" ng-click="$ctrl.save($ctrl.formFields)">Add</button>
              </div>
            <div>
          </div>
        `,
        controller: testModal2Controller
    })
    .name;

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

        var ctrl = this;

        ctrl.groups = [ { name: 'group1' }, { name: 'group2' }, {name: 'group3'} ];

        ctrl.$onInit = function() {

            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;

            for (let i = 0; i < 10; i++) {
                ctrl.templates.push({ name : 'template' + i });
            }

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

                    ctrl.next();
                }
            } else {
                ctrl.cancel('Templates are not found');
            }
        }

        function getFields() {
            // todo get formFields from server
            for (let i = 0; i < 2; i++) {
                ctrl.formFields.push({
                    label: 'field' + i,
                    type: 'java.lang.String',
                    value: 'gr1',
                    group: 'group1'
                });
            }
            ctrl.formFields.push({
                label: 'field2',
                type: 'java.lang.String',
                value: 'gr1',
                group: 'group1',
                tag: ['group1', 'group3']
            });
            for (let i = 3; i < 5; i++) {
                ctrl.formFields.push({
                    label: 'field' + i,
                    type: 'java.lang.String',
                    value: 'gr2',
                    group: 'group2'
                });
            }
            ctrl.formFields.push({
                label: 'field5',
                type: 'java.lang.String',
                value: 'gr3',
                group: 'group3',
                tag: ['group1', 'group3']
            });
        }

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

            if (!ctrl.formFields || ctrl.selectedItem.name !== ctrl.formFields[0].value) {
                ctrl.formFields = [];

                ctrl.formFields.push({
                    label: 'factoryId',
                    type: 'java.lang.String',
                    value: ctrl.hasSteps ? ctrl.selectedItem.name : ctrl.templates[0].name,
                    readOnly: true,
                    required: true
                });

                getFields();

                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);
        }

        ctrl.changeSelection = function(item) {
            ctrl.selectedItem = item;
        }

//        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: 'testModal2',
//                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') {
//                        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;
        }
    }
    testModal2Controller.$inject = ['workspace', '$uibModal'];

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