'use strict';

import { getLang } from "../lang.js";

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

    function reducer(state = {}, action){
        switch(action.type){
            case 'set':
                state[action.name] = action.value;
                return state;
            case 'delete':
                delete state[action.name];
                return state;
            case 'clear':
                return {};
            case 'get':
            default:
                return state;
        }
    }

    let store = window.RTK.createStore(reducer);

    function select(state, property) {
        return state[property] || '';
    }

    let currentState = {};
    store.subscribe(() => {
        m.redraw();
        [ 'call-button', 'call-block', 'call-notification'].map(item => {
            let element = document.getElementById('call-block');
            if(element.children.length > 1){
                element.removeChild(element.children[0]);
            }
        })
        let methods = Object.keys(store.getState()).filter((item) => item.match('___') != null);
        for(let method of methods){
            let previousValue = select(currentState, method.split('___')[0]);
            let currentValue = select(store.getState(), method.split('___')[0]);
            if (previousValue !== currentValue) {
                store.getState()[method]();
            }
        }

        for(let key in store.getState()){
            currentState[key] = store.getState()[key];
        }
    });

    return {
        get: function(name){
            if(!(!!store.getState()[name])){
                if(Lockr.get(name)){
                   this.set(name, Lockr.get(name));
                }
            }
            return store.getState()[name];
        },
        set: function(name, value, use_local_storage = true){
            if(!(value instanceof Function) && use_local_storage){
                Lockr.set(name, value);
            }
            store.dispatch({type: 'set', name, value});
        },
        has: function(name){
            if(!(!!store.getState()[name])){
                if(Lockr.get(name)){
                   this.set(name, Lockr.get(name));
                }
            }
            return !!store.getState()[name];
        },
        delete: function(name){
            Lockr.rm(name);
            store.dispatch({type: 'delete', name});
        },
        clear: function(){
            Lockr.flush();
            store.dispatch({type: 'clear'});
        },
        functions: function() {
            return {
                call: store.getState()['call'],
                getCost: async function(phone_numbers = []){
                    if(phone_numbers.length != 0){
                        let result = [];
                        for(let number of phone_numbers){
                            let req = store.getState()['req'];
                            req['phonenumber'] = number;
                            let response = await store.getState()['scall'](store.getState()['params'], 'getPriceByDirection2', req, 'json'); // Выгрузка за период
                            if(response.error_message && response.error_message != ''){
                                result.push(response.error_message);
                            } else if(response.data['price']){
                                result.push(`${response.data['price']} ${response.data['currency']}`);
                            }
                        }
                        return [];
                    }

                    return l["array_number_is_empty"];
                }
            }
        }
    };
}
