'use strict';

(function(window) {
    let exports = {
        ctIncoming: 0, ctOutgoing: 1, ctInternal: 2,
        resAnswered: 0, resNoAnswer: 1, resBusy: 2, resFailed: 3, resOther: 4, resCancelled: 5,
        ivrNone: 0, ivrMenu: 1, ivrTarget: 2, ivrAny: 3,

        convertToDuration: s => {
            return [
                parseInt(s / 60 % 60),
                parseInt(s % 60)
            ].join(":")
            .replace(/\b(\d)\b/g, "0$1")
        },

        prettifyPhone: s => {
            if (s === 'IVR') {
                return 'Меню';
            }

            s = ('' + s).replace(/\D/g, '');

            let match = s.match(/^(7|8|)?8332(\d{6})$/);
            if (match) {
                return [(match[1] && match[1] !== '8') ? '+' + match[1] + ' ' : '+7 ',
                    '(8332) ', match[2]].join('');
            }

            match = s.match(/^(7|8|)?(\d{3})(\d{3})(\d{4})$/);
            if (match) {
                return [(match[1] && match[1] !== '8') ? '+' + match[1] + ' ' : '+7 ',
                    '(', match[2], ') ', match[3], match[4]].join('');
            } else {
                return s;
            }
        },

        uglifyPhone: function(num) {
            num = ('' + num).replace(/\D/g, '');
            let match = num.match(/^(7|8|)?(\d{10})$/);
            if (match) {
                if (match[1] && (match[1] === '7' || match[1] === '8')) {
                    return match[2]
                } else {
                    return [match[1], match[2]].join('');
                }
            }

            return num;
        },

        callTypeToString: function(ct) {
            switch (ct) {
                case exports.ctIncoming: { return "incoming"; }
                case exports.ctOutgoing: { return "outgoing"; }
                case exports.ctInternal: { return "internal"; }
                default: { return ""; }
            }
        },

        toArray: function(a) {
            if (Array.isArray(a)) {
                return a;
            } else if (a === null || a === undefined) {
                return [];
            } else {
                return [a];
            }
        }
    };


    exports.ctMaxSet = ((1 << (Math.max(exports.ctIncoming, exports.ctOutgoing, exports.ctInternal) + 1)) - 1);
    exports.resMaxSet = ((1 << (Math.max(exports.resAnswered, exports.resCancelled) + 1)) - 1);


    exports.getCallType = function(src, dst) {
        if (src.length >= 6) {
            return exports.ctIncoming;
        }

        if (src.length < 6 && dst.length >= 6) {
            return exports.ctOutgoing;
        }

        return exports.ctInternal;
    };

    if ( typeof module === 'object' && module && typeof module.exports === 'object' ) {
        module.exports = exports;
    } else {
        window.common = exports;
    }
}(this))
