/*-
 * ~~~~~~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
        .directive("selectNgFiles", function() {
          return {
            require: "ngModel",
            link: function postLink(scope,elem,attrs,ngModel) {
              elem.on("change", function(e) {
                var files = elem[0].files;
                ngModel.$setViewValue(files);
              })
            }
          }
        })
        .component('entaxyTest', {
            template:
                `<h2>Test</h2>
                <div>
                    <div style="margin-bottom:10px">
                        <p>Test of a modal window with capability of invoking extra modals</p>
                        <button type="button" class="btn btn-default" ng-click="$ctrl.showModal()">
                            Show Modal
                        </button>
                        <hr>
                    </div>

                    <div style="margin-bottom:10px">
                        <p>Test of a modal window, keep it for filter in second step</p>
                        <button type="button" class="btn btn-default" ng-click="$ctrl.showModal2()">
                            Show Modal
                        </button>
                        <hr>
                    </div>

                    <div style="margin-bottom:10px">
                        <p>Test of posting a file to the REST API with getting its id in response</p>
                        <form name="testForm" class="form-horizontal" ng-submit="$ctrl.testRest()">
                            <div class="form-group" ng-repeat="formField in $ctrl.fileFormFields">
                                <label class="col-sm-1 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">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-1 control-label">file</label>
                                <div class="col-sm-7">
                                    <input type="file" select-ng-files ng-model="$ctrl.files"></input>
                                </div>
                            </div>
                            <button type="submit" class="btn btn-default"
                                ng-disabled="!$ctrl.files">Confirm</button>
                        </form>
                    </div>
                    <hr>
                    <div ng-repeat="file in $ctrl.files" style="margin-bottom:10px">
                        <p>File name: {{file.name}}</p>
                    </div>
                    <div ng-if="$ctrl.res" style="margin-bottom:10px">
                        <p>File id: {{$ctrl.res}}</p>
                    </div>
                    <div ng-if="$ctrl.req" style="margin-bottom:10px">
                        <p>Request: {{$ctrl.req}}</p>
                    </div>
                    <div ng-if="$ctrl.fields" style="margin-bottom:10px">
                        <hr>
                        <p>Fields: {{$ctrl.fields}}</p>
                    </div>
                </div>
                `,
            controller: EntaxyTestController
        })
        .name;

    function EntaxyTestController(workspace, $uibModal, $q, jolokia, restService, operationsService) {
        'ngInject';
        var ctrl = this;

        ctrl.fileFormFields = [];
        for (var i = 0; i < 2; i++) {
            ctrl.fileFormFields.push({
                label: 'field' + i,
                value: '',
                type: Entaxy.convertToHtmlInputType('String')
            });
        }

        ctrl.count = 5;
        ctrl.callback = function(amount) {
            ctrl.count += amount;
        }

        ctrl.testRest = function () {

            let file = ctrl.files[0];
            var fd = new FormData();
            fd.append('file', file);

            restService.post('/cxf/fileUpload/post', fd)
            .then((response) => {
                ctrl.res = response.data;

                ctrl.req = ctrl.fileFormFields.map(formField => { return { label: formField.label, value: formField.value }; });
                ctrl.req.push({ label: 'fileId', value: ctrl.res});
            })
            .catch((error) => Core.notification('danger', error, 5000));
        }

        ctrl.options = [{ name: 'first option' }, { name: 'second option' }, { name: 'third option' }];

        function updateFormFields() {
            ctrl.formFields = [];
            ctrl.formFields.push({
                label: 'field0',
                value: '',
                type: Entaxy.convertToHtmlInputType('entaxy.runtime.profile'),
                hasAddButton: true
            });
            for (var i = 1; i < 5; i++) {
                ctrl.formFields.push({
                    label: 'field' + i,
                    value: '',
                    type: Entaxy.convertToHtmlInputType('entaxy.runtime.profile')
                });
            }
        }

        ctrl.showModal = function() {
            updateFormFields();

            $uibModal.open({
                component: 'testModal',
                resolve: {
                    templates: () => [ { name: 'testParent' } ],
                    formFields: () => ctrl.formFields
                },
                size: 'lg',
                backdrop: 'static'
            })
            .result.then(args => {
                ctrl.fields = args;
            });
        }

        ctrl.showModal2 = function() {
            $uibModal.open({
                component: 'testModal2',
                resolve: {
                    templates: () => [ { name: 'test' } ]
                },
                size: 'xl',
                backdrop: 'static'
            })
            .result.then(args => {
                ctrl.res = args;
            });
        }

        ctrl.prepareFile = function() {
            Entaxy.log.info('FILE ' + JSON.stringify(ctrl.files[0]));
            let file = ctrl.files[0];

            let data = ctrl.files[0];
            var fd = new FormData();
            fd.append('file', file);

            restService.post('/cxf/fileUpload/post', fd)
            .then((response) => ctrl.res = response.data);
        }
    }
    EntaxyTestController.$inject = ['workspace', '$uibModal', '$q', 'jolokia', 'restService', 'operationsService'];

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