'use strict';

import { Input } from '../common/input.js';
import { Button } from '../common/button.js';
import { Numpad } from './Numpad.js';
import { getLang } from '../../lang.js';

export function CallBlock(_store, cbext_path){
    let l = getLang(config["lang"] == "russian" ? config["lang"] : "english");
    let store = _store;

    document.addEventListener('click', function(e){
        let path = e.path || (e.composedPath && e.composedPath())
        if(
            !path.includes(document.querySelector('#call-button')) &&
            !path.includes(document.querySelector('#call-block')) &&
            !path.includes(document.querySelector('#call-notification')) &&
            !path.includes(document.querySelector('.call_notification--container')) &&
            !path.includes(document.querySelector('.call_block-buttons_block')) &&
            !path.includes(document.querySelector('.call_block--btn')) &&
            !path.includes(document.querySelector('#edit_form')) &&
            !path.includes(document.querySelector('#iptel_primatel_settings_view'))
        ){
            store.set('is_showed_call_block', false);
            //store.set('phone_number', '');
            store.set('service_text', '');
        }
    });

    return {
        view: function(){
            return store.get('is_showed_call_block') ? m('div', {
                class: 'call-content'
            }, [
                m('div', {
                    class: ''
                }, [
                    m(Input, {
                        id: 'call_block-tel_number',
                        type: 'text',
                        icon: {
                            src: `./${cbext_path}/assets/images/tel.png`,
                            alt: 'tel'
                        },
                        class: 'call_block-tel',
                        placeholder: 'Enter the number',
                        value: store.get('phone_number'),
                        disabled: store.get('is_call'),
                        oninput: function(e) {

                            store.set('phone_number', this.value.replace(/[^\d\+\#\*]/g, ''));
                        },
                        onkeydown: function(e) {
                            if(e.keyCode == 13){
                                store.get('call')();
                            }
                            if ( e.keyCode == 46 || e.keyCode == 8 || e.keyCode == 9 || e.keyCode == 27 ||
                                (e.keyCode == 65 && e.ctrlKey === true) ||
                                (e.keyCode == 67 && e.ctrlKey === true) ||
                                (e.keyCode == 86 && e.ctrlKey === true) ||
                                (e.keyCode == 88 && e.ctrlKey === true) ||
                                (e.keyCode >= 35 && e.keyCode <= 39)
                            ) {
                                return;
                            } else {
                                // Запрещаем все, кроме цифр на основной клавиатуре, а так же Num-клавиатуре
                                if ((e.keyCode < 48 || e.keyCode > 57) && (e.keyCode < 96 || e.keyCode > 105 )) {
                                    e.preventDefault();
                                }
                            }
                        }
                    }),
                    m('div', {
                        class: 'call_block-buttons_block'
                    }, [
                        (store.get('Call') && !(store.get('Call').isCall)) && store.get('showed_call_buttons') ||
                        !store.get('Call') &&  store.get('showed_call_buttons')
                            ? m('button', {
                                class: 'call_block--btn call_block--btn-cost',
                                onclick: async () => {
                                    if(store.get('service_text').length != 0){
                                        store.set('service_text', '');
                                        return;
                                    }
                                    if(trim(store.get('phone_number')).length == 0){
                                        store.set('service_text', l.Number_is_empty + '!');
                                        setTimeout(() => {
                                            store.set('service_text', '');
                                        }, 5000);
                                        return;
                                    }
                                    store.set('cost_button_text', '...');
                                    let req = store.get('req');
                                    req['phonenumber'] = store.get('phone_number');
                                    store.set('req', req);
                                    let result = await store.get('scall')(store.get('params'), 'getPriceByDirection2', store.get('req'), 'json'); // Выгрузка за период
                                    if(result.error_message && result.error_message != ''){
                                        store.set('service_text', result.error_message);
                                    } else if(result.data['price']){
                                        store.set('service_text', `Cost per minute - ${result.data['price']} ${result.data['currency']}`);
                                    }
                                    store.set('cost_button_text', 'Стоимость');
                                }
                            }, store.get('cost_button_text') == 'Стоимость' || store.get('cost_button_text') == void 0
                                ? m('img', {
                                    style: 'width: 19px; height: 19px;',
                                    src: `./${cbext_path}/assets/images/coins.svg`,
                                    alt: 'Cost'
                                })
                                : store.get('cost_button_text')
                            )
                            : m('div', { style: 'width: 15%;' }),
                        (store.get('Call') && !store.get('Call').isCall || !!!store.get('Call')) && store.get('showed_call_buttons')
                            ? m(Button, {
                                class: 'call_block--btn call_block--btn-call',
                                onclick: () => {
                                    store.get('call')();
                                },
                            }, 'Call')
                            : null,
                        (
                            store.get('Call') && store.get('Call').isCall && !!!store.get('is_call') &&
                            (store.get('iSession') && Object.keys(store.get('iSession')).length > 0) &&
                            store.get('call_type') == 'incoming'
                        )
                            ? m(Button, {
                                class: 'call_block--btn call_block--btn-answer',
                                onclick: store.get('callAnswer')
                            }, 'Answer')
                            : null,
                        (store.get('Call') && store.get('Call').isCall)
                            ? m(Button, {
                                class: 'call_block--btn  call_block--btn-reject',
                                style: !(store.get('iSession') && Object.keys(store.get('iSession')).length > 0) ? 'width: 100%' : '',
                                onclick: store.get('call_type') == 'incoming' ? store.get('incomingHangUp') : store.get('hangUp'),
                            }, 'Reject')
                            : null,
                        (store.get('Call') && store.get('Call').isCall) &&
                        store.get('call_type') == 'outgoing'
                            ? m('div', { style: 'width: 35%;' })
                            : null,
                        (
                            store.get('Call') && store.get('Call').isCall && !!store.get('is_call') &&
                            (store.get('iSession') && Object.keys(store.get('iSession')).length > 0) &&
                            store.get('call_type') != 'outgoing'
                        )
                            ? m(Button, {
                                class: 'call_block--btn  call_block--btn-redirect',
                                onclick: store.get('startForwardCall')
                            }, 'Forward')
                            : null,
                        store.has('_ua')
                            ? m('button', {
                                class: 'call_block--btn call_block--btn-numpad',
                                onclick: (e) => {
                                    e.preventDefault();
                                    if(!store.has('show_number_block')){
                                        store.set('show_number_block', true);
                                    }
                                    else {
                                        store.set('show_number_block', !store.get('show_number_block'));
                                    }
                                }
                            }, m('img', {
                                src: `./${cbext_path}/assets/images/keypad.svg`
                            }))
                            : m('div', { style: 'width: 15%;' }),
                    ]),
                    m('div', {
                        style: 'width: 253px;'
                    }, store.get('service_text') || ''),
                    store.get('show_redirect_block')
                        ? m('div', {
                            class: 'call_block-forward'
                        }, [
                            m('select', {
                                onchange: function(){
                                    store.set('redirect_number', this.value);
                                }
                            }, [{ id: 0, name: '', short_number: '' }, ...store.get('users_info')].map(item => m('option', {
                                value: item.short_number,
                            }, item.name))),
                            m('button', {
                                class: '.call_block--btn',
                                onclick: store.get('forwardCall')
                            }, m('img', {
                                src: `./${cbext_path}/assets/images/call-forwarding.png`
                            }))
                        ])
                        : null,
                    store.has('show_number_block') &&
                    store.get('show_number_block') &&
                    (store.get('_ua') &&
                    Object.keys(store.get('_ua')).length > 0)
                        ? m(Numpad, { store })
                        : m('div', { style: 'width: 15%' })
                ])
            ]) : null;
        }
    }
}
