/*-
 * ~~~~~~licensing~~~~~~
 * 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 Entaxy1CCommunication;
(function (Entaxy1CCommunication) {
    Entaxy1CCommunication._module
    .component('entaxy1cCommunicationDemo', {
        template:
        `
          <!-- // fixme style -->
          <div style="padding: 0 20px;">
            <!-- // fixme style -->
            <div style="display: flex; justify-content: space-between; align-items: center;">
              <h2>
                Тестовое Приложение для 1С
              </h2>

              <div>
                <!-- // fixme style -->
                <button type="button" ng-if="!$ctrl.isStopped" ng-click="$ctrl.stop()" style="width: 90px; height: 25px; margin-top: 5px;">Остановить</button>
                <!-- // fixme style -->
                <button type="button" ng-if="$ctrl.isStopped" ng-click="$ctrl.start()" style="width: 90px; height: 25px; margin-top: 5px;">Запустить</button>
                <button type="button" ng-click="$ctrl.showSettingsModal()" style="width: 90px; height: 25px; margin-top: 5px;">Настройки</button>
              </div>
            </div>

            <pf-table-view config="$ctrl.tableConfig"
                          columns="$ctrl.tableColumns"
                          action-buttons="$ctrl.tableActionButtons"
                          page-config="$ctrl.pageConfig"
                          items="$ctrl.viewedItems"
                          empty-state-config="$ctrl.emptyStateConfig">
            </pf-table-view>

          </div>
        `,
        controller: Entaxy1CCommunicationScopesController
    })
    .name;

    function Entaxy1CCommunicationScopesController(workspace, $scope, $interval, $q, soapService, xml2JsonService, $uibModal) {
        'ngInject';

        var ctrl = this;
        ctrl.workspace = workspace;

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

        ctrl.emptyStateConfig = {
            title: 'Сообщения Отсутствуют'
        };

        ctrl.tableColumns = [
            { header: 'UUID Сообщения', itemField: 'uuid' },
            { header: 'Наименование', itemField: 'name' }
        ];

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

        let readMessages;

        $scope.startReading = function() {
            if (angular.isDefined(readMessages)) return;

            readMessages = $interval(populateTable, 15000);
        }

        $scope.stopReading = function() {
            if (angular.isDefined(readMessages)) {
                $interval.cancel(readMessages);
                readMessages = undefined;
            }
        }

        $scope.$on('$destroy', function() {
            $scope.stopReading();
        });

        ctrl.items = [];
        ctrl.viewedItems = [];

        ctrl.$onInit = function() {
            ctrl.profileName = 'system-crm';
            ctrl.forwardedUser = 'system-crm';
            populateTable();
            $scope.startReading();
        }

        function populateTable() {
            getItem().then((item) => {
                if (item) {
                    ctrl.items.push(item);
                    ctrl.viewedItems = ctrl.items;
                }
            });
        }

        ctrl.stop = function () {
            ctrl.isStopped = true;
            $scope.stopReading();
        }

        ctrl.start = function () {
            ctrl.isStopped = false;
            populateTable();
            $scope.startReading();
        }

        function getItem () {
            let deferred = $q.defer();

            let bodyGet = getBodyForGetMethod(ctrl.profileName);

            soapService.execute(bodyGet, ctrl.forwardedUser, '/uniform-exchange')
            .then((bodyResponse) => {

                if (bodyResponse != null) {

                    let packet = bodyResponse.packets[0].packet[0];

                    let messageUuid = packet.header[0].transportUUID[0]['#text'];

                    let bodyAck = getBodyForAckMethod(messageUuid);
                    soapService.execute(bodyAck, ctrl.forwardedUser, '/uniform-exchange');

                    let messageContent = packet.message[0].content[0];
                    let messageContentParsed = xml2JsonService.xml2json(messageContent['#text']);
                    let name = messageContentParsed.classData[0]['Наименование'][0]['#text'];

                    deferred.resolve({ uuid: messageUuid, name: name });

                }

                deferred.resolve(null);

            }).catch(error => {
                Core.notification('danger', error, 5000);
                Entaxy1CCommunication.log.error(error);
            });

            return deferred.promise;
        }

        function getBodyForGetMethod(destinationId) {
            return '<ns:getPacketsRequest>' +
                        '<ns:destination>' +
                            '<ns:id>' + destinationId + '</ns:id>' +
                            '<ns:type>system.name</ns:type>' +
                        '</ns:destination>' +
                        '<ns:limitCount>1</ns:limitCount>' +
                        '<ns:limitSize>0</ns:limitSize>' +
                    '</ns:getPacketsRequest>';
        }

        function getBodyForAckMethod(messageUuid) {
            return '<ns:uuids><ns:uuid>' + messageUuid + '</ns:uuid></ns:uuids>';
        }

        ctrl.showSettingsModal = function () {
            $uibModal.open({
                component: 'entaxy1cCommunicationDemoSettingsModal',
                resolve: {
                    forwardedUser: () => ctrl.forwardedUser,
                    destinationId: () => ctrl.profileName
                },
                backdrop: 'static'
            })
            .result.then(fields => {
                let args = fields.reduce((obj, cur) => ({ ...obj, [cur.name] : cur.value }), {});
                ctrl.forwardedUser = args['forwardedUser'];
                ctrl.profileName = args['destinationId'];
            },
            reason => {
                if (reason) {
                    Core.notification('danger', reason, 5000);
                }
            });
        }

    }
    Entaxy1CCommunicationScopesController.$inject = ['workspace', '$scope', '$interval', '$q', 'soapService', 'xml2JsonService', '$uibModal'];

})(Entaxy1CCommunication || (Entaxy1CCommunication = {}));
