/**
 * @var feather
 */

$().ready(() => {

    feather.replace()

    setWindowFunction('removeAgent', removeAgent)
    setWindowFunction('toggltAgentDnd', toggltAgentDnd)
    setWindowFunction('addAgent', addAgent)

    $('#queues_add').on('click', function () {
        swal.fire({
            title: 'Введите номер очереди',
            input: 'text',
            inputAttributes: {
                autocapitalize: 'off',
                placeholder: 'Номер очереди',
                id: 'add_queue_inp',
            },
            preConfirm: (val) => {
                if (!val) {
                    Swal.showValidationMessage(
                        `Введите номер очереди`
                    )
                    return false;
                }
                if (val.replace(/\d+/g, '')) {
                    Swal.showValidationMessage(
                        `Некорректный номер очереди`
                    )
                    return false;
                }
                return true;
            },
            showCancelButton: true,
            cancelButtonText: 'Отмена',
        }).then((result) => {
            if (result.isConfirmed) {
                var val = $('#add_queue_inp').val();
                
                if (val) {
                    addNewQueue(val);
                }
            }
          });
    })

    /**
     * if there is no function under key {key} add it to window
     * @param {String} key 
     * @param {Function} func
     * @returns {void} 
     */
    function setWindowFunction(key, func) {
        if (typeof window[key] !== 'function') {
            window[key] = func
        }
    }

    /**
     * remove agent from queue
     * @param {String} agentId 
     * @returns {void}
     */
    function removeAgent (agentId, queue) {
        uiLoading();
        const agent = window.Queues.agents.get(agentId);
        if (!agent) {
            console.warn(agentId + ' is not defined');
            return;
        }

        doAloVoiceCmd('delMemeberQueue', {
            queue:  queue,
            member: agent.number
        }, function() {
            uiLoadingEnd();
            alert(agent.number + ' удален из очереди ' + queue);
        });
    }

    window.addAgentToQueue = function (queue) {
        var list = getCurrentUsersAr(queue);
        var el = createMembersList(list);

        swal.fire({
            title: 'Добавить в '+ queue,
            html: el,
            // backdrop: 'rgb(0 0 0 / 0%)'
            showCancelButton: true,
            cancelButtonText: 'Отмена',
            confirmButtonText: 'Добавить',
            didOpen: function () {
                $('[name="add_member"]').on('change', function () {
                    var target = '[for="' + this.id+ '"]';
                    if ($(this).is(':checked')) {
                        $(target).addClass('btn-success').removeClass('btn-light');
                    } else {
                        $(target).removeClass('btn-success').addClass('btn-light');
                    }
                })
            }
        }).then(function (result) {
            if (result.isConfirmed) {
                // $('[name="add_member"]:checked').each(function () {
                //     var value = $(this).val();

                //     if (!value) {
                //         return;
                //     }

                //     addAgent(value, queue);
                // });
                uiLoading();
                addMember($('[name="add_member"]:checked'), 0);
            }
        });

        function addMember (elements, index) {
            if (elements.length-1 < index) {
                uiLoadingEnd();
                return;
            }
            var el = elements[index];

            if (!el) {
                return;
            }

            // return
            addAgent(el.value, queue, function () {
                addMember(elements, index+1);
            });
        }
    }

    window.uiLoading = function () {
        $('body').append(`<div class="app-loading d-flex align-items-center justify-content-center">${feather.icons['loader'].toSvg({class: 'app-loading__icon'})}</div>`);
    }

    window.uiLoadingEnd = function () {
        $('.app-loading').remove();
    }

    window.addNewQueue = function (queue) {
        uiLoading();
        doAloVoiceCmd('addNewQueue', {
            number:  queue,
        }, function() {
            uiLoadingEnd();
            alert('Очередь ' + queue + ' добавлена');
        });
    }
    window.removeQueue = function (queue) {
        uiLoading();        
        doAloVoiceCmd('removeQueue', {
            queue:  queue,
        }, function() {
            uiLoadingEnd();
            $('[queue-nav]:first').trigger('click');
            alert('Очередь ' + queue + ' удалена');
        });
    }

    function createMembersList (list) {
        var div = $('<form class="" style="max-height: 300px;max-height: calc(60vh - 100px);" />');

        // div.append('');

        $.each(list, function (none, data) {
            div.append(`<div class="mb-2">
                <label class="d-block btn btn-light py-2 mb-0" for="member_${data.number}" style="cursor: pointer;">
                    <span class="mr-4">${data.number} </span>
                    <span>${data.fullname}</span>
                </label>
                <input name="add_member"
                    type="checkbox"
                    id="member_${data.number}" 
                    value="${data.number}"
                    style="display: none;">
            </div>`);
        });

        return div.get(0);
    }
    
    function getCurrentUsersAr (queue) {
        var result = [];
        var queueMembers, allMembers, queueData;
        if (!window.Queues && !window.Queues.data) {
            return result;
        }
        queueData = window.Queues.data.queues[queue];
        allMembers = window.Queues.data.agents || {};
        if (!queueData) {
            return result;
        }
        queueMembers = queueData.QueueMember || {};

        $.each(allMembers, function (number, data) {
            if (number in queueMembers) {
                return;
            }

            result.push(data);
        });

        return result;
    }

    function addAgent (number, queue, success) {
        doAloVoiceCmd('addMemeberQueue', {
            queue:  queue,
            member: number
        }, function() {
            alert(number + ' добавлен в очередь ' + queue);

            if (typeof success === 'function') {
                success();
            }
        });
    }

    /**
     * toggle agent dnd status
     * @param {String} agentId 
     * @returns {void}
     */
    function toggltAgentDnd (number) {
        if (!number) {
            return;
        }
        uiLoading();
        loadAloVoiceInfo({
            restmethod:'alovoice_dnd_toggle', 
            number: number, 
            // status:'off'
        }, function (r) {
            console.warn("RES:", r);
            uiLoadingEnd();
            if (r.status === 'on') {
                alert(number + ' DND включен');
            } else {
                alert(number + ' DND выключен');
            }
            
        });
    }
})

function getQuesue() {

    /**
     * @class Quesue
     * @param {{
     *  data: {
     *      agents: Array
     *  },
     *  locale: Object, 
     *  params: Object, 
     *  target: Object
     * }} data 
     */
    function Quesue(data) {
        const self = this
        this.data = this._toCurrentAgentData(data.data)
        // this.target = data.target
        this.locale = data.locale
        this.params = data.params

        this.__setAgents(data.data.agents)

        this.$target = {}
        $.each(data.target, function(key, value) {
            self.$target[key] = $(value)
        })

        this.footerActivePill = 0

        this._conf = {
            calls: {
                keys: {
                    ivr: ['ivr'],
                    in: ['Incom'],
                    out: ["Out", "Outlines"],
                }
            }
        }
    }

    Quesue.prototype = {
        /**
         * 
         */
        init() {
            const data = this.data
            this._channels = this._getCurrentQueuesCalls(data.channels)

            this.$target.agents.append(
                this.renderQueuesBar(Object.keys(data.queues))
            )

            this.$target.queues.html(
                this.renderChannelsBar(this._channels)
            )

            this.$target.agents.append(
                this.agentsController(data.queues)
            )

            return true
        },

        getAgentQueue(number) {
            // this.data
            var result = '';
            if (!this.data.queues) {
                return result;
            }
            $.each(this.data.queues, function (key, data) {
                if (data.QueueMember && number in data.QueueMember) {
                    result = key;
                }
            });

            return result;
        },

        /**
         * update ques data
         * @param {Object} newData 
         * @returns {Boolean}
         */
        update(newData) {
            newData = this._toCurrentAgentData(newData)
            const self = this
            const prevData = this.data;
			this._channels = this._getCurrentQueuesCalls(newData.channels)

            this.channels = newData.channels
            this.__setAgents(newData.agents)
            this.data = newData

            $.each(prevData.queues, (index, value) => {
                // get current data
                if (newData.queues[index]) {
                    const data = self.__getUpdateResult(
                        value.QueueMember, newData.queues[index].QueueMember
                    )
    
                    self._update(data, index)
                } else {
                    $(`[queue-nav="${index}"`).remove();
                    $(`[data-queue-number="${index}"`).remove();
                }
            })

            
            this.$target.queues.html(
                this.renderChannelsBar(this._channels)
            )

            return true
        },

        _toCurrentAgentData(data) {
            var agents = {};
            
            Object.entries(data.agents).map(function(arr) {
                var key = arr[0], value = arr[1];

                if (value.connect && value.status === 'off') {
                    value.status = 'free'
                }

                agents[key] = value
            })

            data.agents = agents
            return data
        },

        /**
         * uppdate queue 
         * @private
         * @param {Object} data queue data
         * @param {Number|String} queue queue number
         * @returns 
         */
        _update(data, queue) {
            const self = this
            const nav = $(`[queue-nav='${queue}']`).get(0)

            if (Array.isArray(data.new) && data.new.length) {
                this._updateAddNew(data.new, queue)
            }
            if (Array.isArray(data.remove) && data.remove.length) {
                this._updateRemove(data.remove, queue)
            }

            if (Array.isArray(data.data) && data.data.length) {
                this._updateData(data.data, queue)
            }

            if (!nav) {
                const $target = $(`#queues__container`)
                const navs = $(`[queue-nav]`).length

                $target.append(
                    self.quesusItemView({
                        index: navs,
                        value: queue,
                        isActive: false
                    })
                )

                $(`#queues_tab_content`).append(
                    self.agentsContainer({
                        data: data, 
                        index: navs, 
                        isActive: false,
                        queue: queue
                    })
                )
            }

            return true
        },

        /**
         * Adds a new agent to the queue
         * @private _updateAddNew
         * @param {Array} data - Array of users 
         * @param {String} queue - queue number
         * @returns {void}
         */
        _updateAddNew(data, queue) {
            const self = this;
            const $target = $(`[data-queue-number="${queue}"] .row:first .add_agent_div`)

            if ($target.length) {
                $target.before(
                    data.map(d => {
                        const agent = self.agents.get(d.number)

                        return self.agentsView({
                            data: agent,
                            params: d
                        })
                    })
                )
            }
        },
        /**
         * remove agent from the queue
         * @private _updateRemove
         * @param {Array} data - Array of users 
         * @param {String} queue - queue number
         * @returns {void}
         */
        _updateRemove(data, queue) {
            const $target = $(`[data-queue-number="${queue}"]`)

            if ($target.length) {
                data.map(d => $target.find(`[data-queue-agent=${d.number}]`).remove())
            }
        },
         /**
         * updates the queue data
         * @private _updateData
         * @param {Array} data - Array of users 
         * @param {String} queue - queue number
         * @returns {void}
         */
        _updateData(data, queue) {
            const self = this
            const $target = $(`[data-queue-number="${queue}"]`)

            if ($target.length) {
                data.map(d => {
                    // const agent = self.agents.get(d.name)
                    const agent = self.agents.get(d.number)
                    if (!agent) {
                        return 
                    }
                
                    const call = this._getAgentCall(agent.number, agent.status) || {}
                    const $el = $target.find(`[data-queue-agent=${agent.number}]`)
                                     
                    if(typeof self.channels.Incom != 'undefined' && typeof self.channels.Incom[agent.number] != 'undefined'){
                        inCall = self.channels.Incom[agent.number];
                    }
                    if(typeof self.channels.Out != 'undefined' && typeof self.channels.Out[agent.number] != 'undefined'){
                        outCall = self.channels.Out[agent.number];
                    }                        

                    $el.children().css('background-color', self._getAgentStatusColor(agent.status));

                    $el.find('[data-agent="name"]').html(agent.name)
                    $el.find('[data-agent="status"]').html(self._getAgentStatusValue(agent, call))
                    $el.find('[data-agent="buttons"]').html(self._getAgentButtons(agent, d))
                    return true
                })
            }
        },

        /**
         * returns an object with elements to remove, update, add 
         * @param {Array} oldData 
         * @param {Array} newData 
         * @returns {Object} 
         */
        __getUpdateResult(oldData, newData) {
            let result = {
                new: [],    // add elements
                remove: [], // remove elements
                data: []    // update elements
            }

            if (!(typeof oldData === "object" && typeof newData === 'object')) {
                return result
            }
            
            return ({
                data: getUpdates(newData, oldData),
                new: getNews(newData, oldData),
                remove: getRemoves(newData, oldData)
            });

            function getUpdates (newData, curretData) {
                var result = [];

                $.each(newData, function (key, data) {
                    if (curretData[key]) {
                        result.push(data);
                    }
                });

                return result;
            }
            function getNews (newData, curretData) {
                var result = [];

                $.each(newData, function (key, data) {
                    
                    if (!curretData[key]) {
                        result.push(data);
                    }
                });

                return result;
            }
            function getRemoves (newData, curretData) {
                var result = [];

                $.each(curretData, function (key, data) {
                    if (!newData[key]) {
                        result.push(data);
                    }
                });

                return result;
            }
        },

        /**
         * render queues bar to target
         * @param {JQElement} target
         * @param {Array} data - array with queues and agents
         * @returns 
         */
        renderQueuesBar(data) {
            if(!Array.isArray(data)) {
                console.error("Typeof data isn't Array")
                return ''
            }
            const self = this
            const view = $(`<nav class="row">
                <div class="col-2">${this.locale.queues}</div>
                <div class="col-10">
                    <ul class="nav nav-pills mr-auto" id="queues__container"></ul>
                </div>
            </nav>`)
            const cont = view.find(".nav-pills")
    
            cont.append(
                data.map((value, index) => {
                    return self.quesusItemView({
                        index: index,
                        value: value,
                        isActive: isActive(index)
                    })
                })
            )

            return view

            function isActive (i) {
                return i === self.footerActivePill
            }
        },

        /**
         * render call queue bar
         * @param {Object} data 
         */
        renderChannelsBar(data) {
            const self = this
            const view = $(`<div class="bg-light p-2">
                    <div class="text-center">
                        <h5>${this.locale.channelsTitle}</h5>
                    </div>
            </div>`);
            const cont = $(`<div></div>`);
            
            if (typeof data === "object") {
                $.each(data, (key, d) => {
                    cont.append(
                        self.callQueueSection(d.title, d.data)
                    )
                })
            }
            
            view.append(cont)

            return view
        },

        /**
         * render channel observer NO_USED
         * @param {JQElement} target 
         * @param {Object} data 
         */
        renderObservers(target, data) {
            const view = $(`<div class="p-1 bg-light">
                <div class="text-center font-weight-bold">
                    ${data.TEXT}
                </div>
            </div>`);
            const cont = $(`<div></div>`);

            // cont.append(
            //     this.observersController(data.DATAS)
            // )
            
            target.append(
                view.append(
                    cont.append(
                        this.observersController(data.DATAS)
                    )
                )
            )
        },

        /**
         * render queue agents container with agens
         * @param {JQElement} target 
         * @param {Object} data 
         */
        agentsController(data) {
            const self = this
            const keys = Object.keys(data)
            // craete tab container 
            const tabVont = $(`<div class="tab-content" id="queues_tab_content"></div>`)

            tabVont.append(
                keys.map((key, index) => self.agentsContainer({
                    data: data[key].QueueMember, 
                    index: index, 
                    isActive: isActive(index),
                    queue: key
                }))
            )

            return tabVont

            function isActive (i) {
                return i === self.footerActivePill
            }
        },

        /**
         * @param {Object} param0 
         * @returns {String|HTMLElement}
         */
        agentsContainer({data, index, isActive, queue}) {
            const self = this
            const view = $(`<div class="tab-pane ${isActive ? "active" : ""}" role="tabpanel" id="${index}" data-queue-number="${queue}"></div>`)
            const cont = $(`<div class="row"></div>`)

            if (typeof data !== "object" || !Object.keys(data).length) {
                return view.append(cont.html(
                    self.addAgentView(queue)
                ))
            }
            
            const elems = []

            $.each(data, (index, params) => {
                const agent = self.agents.get(params.number)
				
                if (!agent) {
                    return ''
                }

                elems.push(
                    self.agentsView({
                        data: agent, 
                        params: params,
                        index: index
                    })
                )
            })

            view.append(
                cont.append(
                    elems, self.addAgentView(queue)
                ),
            )
    
            return view;
        },

        /**
         * template for agent
         * @param {Object} param0 
         * @returns {String|HTMLElement}
         */
        agentsView({data, params, index}) {
            const self = this
            const call = this._getAgentCall(data.number, data.status) || {}
            const view = `<div class="col-4 p-2" style="position: relative;" data-queue-agent="${data.number}" title="${data.connect} ${data.useragent} ${data.secret}">
                <div class="row align-items-center m-0 px-2 py-1 rounded h-100" style="background: ${this._getAgentStatusColor(data.status)}">
                    ${discription(data.name)}
                </div>
                <div data-agent="buttons">
                    ${this._getAgentButtons(data, params).join('')}
                </div>
            </div>`

            return view;

            function discription(name) {
                const view = `<div class="col-12 p-0">
                    <p class="m-0" data-agent="name">${name}</p>
                    <p class="m-0" data-agent="status">${self._getAgentStatusValue(data, call)}</p>
                </div>`;

                return view;
            }
            function callData(call) {
                if (!call) {
                    return ''
                }
                const view = `<div class="col-12 p-0">
                    <p class="m-0" data-agent="phone">${call.phone1}</p>
                </div>`;
    
                return view;
            }
        },
        addAgentView(queue) {
            const view = `<div class="col-4 p-2 add_agent_div" style="position: relative;" >
                <button type="button" 
                    class="d-flex align-items-center justify-content-center btn btn-light w-100" 
                    style="height: 56px" 
                    onclick="window.addAgentToQueue('${queue}')"
                    data-queue="${queue}">
                ${feather.icons.plus.toSvg()} Добавить агента</button>
            </div>`

            return view;
        },

        /**
         * @private _getAgentStatusValue
         * @param {Object} agent 
         * @param {Object} call 
         * @returns {String}
         */
        _getAgentStatusValue(agent, call) {
            let value = [
                this._getAgentStatusText(agent.status),
                `<br> <span>${call.phone1 || ""} ${call.duration || ""} </span>`
            ]

            return value.join('')
        },

        /**
         * @private
         * @param {} param0
         * @returns {HTMLElement}
         */
        _getAgentButtons(agent, params) {
            const className = "queues_agent_icon rounded-circle d-flex align-icemt-center"
            let result = [
                `<button type="button" class="${className} bg-white text-danger mr-4" 
                    title="Удалить из очереди"
                    onclick="window.removeAgent('${agent.id}', '${params.queue}')"
                    >${feather.icons['trash'].toSvg({class: "w-100 h-100"})}</button>`,                    
            ]

            if (agent.dnd === 'Y') {
                result.push(`<button type="button" class="${className} bg-white"
                    onclick="window.toggltAgentDnd('${agent.number}')" 
                    title="Выключить DND">${feather.icons['phone-missed'].toSvg({class: "w-100 h-100"})}</button>`)
            } else {
                result.push(`<button type="button" class="${className} bg-white"
                    onclick="window.toggltAgentDnd('${agent.number}')" 
                    title="Включить DND">${feather.icons['phone-incoming'].toSvg({class: "w-100 h-100"})}</button>`)
            }

            // switch (agent.status) {
            //     case 'off':
            //         result.push(`<button type="button" class="${className} bg-white" onclick 
            //             title="off">${feather.icons['phone-missed'].toSvg({class: "w-100 h-100"})}</button>`)
            //         break
            //     case 'free':
            //         result.push(`<button type="button" class="${className} bg-white" onclick 
            //             title="2">${feather.icons['phone-incoming'].toSvg({class: "w-100 h-100"})}</button>`)
            //         break
            //     case 'dnd':
            //         result.push(`<button type="button" class="${className} bg-white"
            //             onclick="window.toggltAgentDnd('${agent.number}')" 
            //             title="3">${feather.icons['phone-incoming'].toSvg({class: "w-100 h-100"})}</button>`)
            //         break
            //     case 'incring':
            //         result.push(`<button type="button" class="${className} bg-white" onclick 
            //             title="4">${feather.icons['phone-incoming'].toSvg({class: "w-100 h-100"})}</button>`)
            //         break
            //     case 'inccall':
            //         result.push(`<button type="button" class="${className} bg-white" onclick 
            //             title="5">${feather.icons['phone-incoming'].toSvg({class: "w-100 h-100"})}</button>`)
            //         break
            //     case 'outring':
            //         result.push(`<button type="button" class="${className} bg-white" onclick 
            //             title="6">${feather.icons['phone-incoming'].toSvg({class: "w-100 h-100"})}</button>`)
            //         break
            //     case 'outcall':
            //         result.push(`<button type="button" class="${className} bg-white" onclick 
            //             title="7">${feather.icons['phone-incoming'].toSvg({class: "w-100 h-100"})}</button>`)
            //         break
            // }

            return result
        },

        /**
         * retorns status color
         * @param {Number} status 
         * @returns {Object}
         */
        _getAgentStatusColor(status) {
            const stcolor = this.params.agents.statuscolor
			
            return stcolor[status] || '#CCCCCC'
        },
        _getAgentCall(agentId, status) {
            const self = this
            let result
            getCall.bind(this)
            
            switch (status) {
                case "incring":
                case "inccall":
                    result = getCall(agentId, "in")
                    break
                case "outring":
                case "outcall":
                    result = getCall(agentId, "out")
                    break
            }

            if (result) {
                result = this._getCurrentCallData(result)
            }

            return result

            function getCall(agentId, key) {
                const calls = self._channels[key].data
                let result

                $.each(calls, (none, call) => {
                    if (call._agentNumber !== agentId) {
                        return
                    }

                    result = call
                })

                return result
            }
        },
        _getAgentStatusText(status) {
			const stcode = this.params.agents.statuscode

            return stcode[status] || '-----'
        },

        /**
         * template for queues bar item 
         * @param {Object} param0 
         * @returns {String|HTMLElement}
         */
        quesusItemView({
            index,
            isActive,
            value
        }) {
            const self = this
            const view = $(`<li class="nav-item">
                <a class="nav-link ${isActive ? "active" : ""}" href="#${index}" data-toggle="pill" aria-expanded="${isActive}" queue-nav="${value}">
                    ${value}
                    <button type="button" class="ml-1 align-middle text-danger" onclick="window.removeQueue('${value}')">
                        ${feather.icons['trash'].toSvg({
                            width: '18px',
                            height: '18px'
                        })}
                    </button>
                </a>
            </li>`)

            view.on("click", function () {
                const $el = $(this);
                const parent = $el.parent();
    
                self.footerActivePill = index;
            })    

            return view;
        },

        /**
         * 
         * @param {Object} data 
         * @returns {String|HTMLElement}
         */
        callQueueSection(title, data) {
            const self = this
            const view = $(`<div class="mb-3">
                <div class="text-center font-weight-bold">${title}</div>
            </div>`)
            const cont = $(`<div></div>`)

            view.append(
                cont.append(
                    self.queuesController(data)
                )
            )
    
            return view
        },

        /**
         * 
         * @param {Object} data 
         * @returns {Array}
         */
        queuesController(data) {
            const self = this
            if(!Array.isArray(data)) {
                return ''
            }

            if(data.length === 0) {
                return `<p class="text-center">${this.locale.queuesEmpty}</p>`
            }

            return data.map((d, i) => {
                const current = self._getCurrentCallData(d)

                return self.queueCallView(current, i+1)
            })
        },

        /**
         * 
         * @param {Object} data 
         * @returns {String|HTMLElement}
         */
        queueCallView(data, key) {
            const view = $(`<div class="row align-items-center p-1 m-0 mt-1"
              style="background: ${data.bgColor}">
                ${keyView(key)} ${phoneView(data.phone1)}${phoneView(data.phone2)} ${timeView(data.duration)}
            </div>`)

            function keyView(val="") {
                const view = `<div class="col-1 p-0">${val}</div>`

                return view
            }
            function titleView(title="", info="") {
                const view = `<div class="col-auto p-0"> ${title} <span>${info}</spam> </div>`;
    
                return view
            }
            function phoneView(phone="") {
                const view = `<div class="col-4 p-0">${phone}</div>`
    
                return view
            }
            function phoneToView(phone="") {
				if(!phone.length){ return "";}
                const view = ` <div class="col-4 p-0">${phone}</div>`
    
                return view
            }
            function timeView(duration="") {
                const view = `<div class="col-2 p-1 bg-light rounded d-flex justify-content-center ml-auto">${duration.substr(-5)}</div>`
    
                return view
            }
    
            return view
        },

        /**
         * Takes call data and converts it to a standard form
         * @param {Object} data 
         * @returns {Object}
         */
         _getCurrentCallData(data) {
            let result = {
                queue: "",
                phone1: "",
                phone2: "",
                duration: "",
            }
			
			// console.log("CHECK: ", "_getCurrentCallData", data);
			
            switch (data._type) {
                case "ivr":
					// IVR 
                    result.phone1 = data.calleridnum // номер звонящего
                    result.phone2 = data.language // внутренний номер агента
                    //result.queue = "" //data.queue_number // номер очереди агента
                    break
                case "incom":
                    // входящий выхов 
                    result.phone1 = data.calleridnum // номер звонящего
                    result.phone2 = (data._agentNumber) ? data._agentNumber : data.connectedlinenum // внутренний номер агента
                    result.queue = data.queue_number // номер очереди агента
                    break
                case "out":
                    // исходящий выхов 
                    result.phone1 = data.outnum // исходящий номер
                    result.phone2 = data._agentNumber || data.calleridnum // || data.connectedlinenum // внутренний номер агента || номер 
                    result.queue = data.queue_number // номер очереди агента
                    break
                case "outlines":
                    // внутренний входящий номер
                    result.phone1 = data.calleridnum // номер
                    result.phone2 = data._agentNumber || data.calleridnum // внутренний номер агента || номер 
                    // result.queue = data.queue_number // номер очереди агента
                    break
            }

            result.duration = data.duration

			// console.log("CallRES: ",result);
			
            return result
        },

        _getCurrentQueuesCalls(data) {
            let result = {
                ivr: {
                    title: 'IVR',
                    data: []
                }, 
				in: {
                    title: 'Входящие',
                    data: []
                },
                out: {
                    title: 'Исходящие',
                    data: []
                }
            }

            setData("ivr", this._conf.calls.keys.ivr)
            setData("in", this._conf.calls.keys.in)
            setData("out", this._conf.calls.keys.out)

            return result

            function setData(mainKey, args) {
                $.each(args, (none, key) => {
                    const k = key.toLocaleLowerCase()
                    $.each(data[key], (phone, value) => {
                        if (k === 'outlines') {
                            if (value.channelstate == 5) {
                                return
                            }
                        }

                        value = $.extend({}, value)
                        value._agentNumber = phone
                        value._type = key.toLocaleLowerCase()
                        result[mainKey].data.push(value)
                    })
                })
            }
        },

        /**
         * 
         * @param {Array} data 
         * @returns {Array} array with html elements
         */
        observersController(data) {
            const self = this
            if(!Array.isArray(data)) {
                return ''
            }
    
            return data.map(d => {
                return self.observerView(d)
            })
        },

        /**
         * tempalte for observers
         * @param {Object} data 
         * @returns {String|HTMLElement}
         */
        observerView(data) {
            const {
                IMG,
                USER
            } = data;
            const view = `<div class="row align-items-center m-0 mt-2 p-1">
                <div class="col-2">
                    <img src="${IMG}" 
                      class="w-100 rounded-circle">
                </div>
                <div class="col-8">
                    <p class="m-0">${USER}</p>
                </div>
            </div>`;
    
            return view;
        },

        /**
         * 
         * @private __setAgents
         * @param {Array} agents 
         * @returns {Map}
         */
        __setAgents(agents) {
            let map = new Map()

            $.each(agents, function(i, agent) {
                map.set(agent.number, agent)
            })

            this.agents = map
            return map
        }
    }

    return Quesue
}
