import axios from "axios";
import marked from "marked";
import dompurify from "dompurify";
import { XmlConverter } from "@/libs/xml-converter/xml-converter";
const converter = new XmlConverter();

function toHtml(txt) {
    marked.setOptions({
        renderer: new marked.Renderer(),
        gfm: true,
        tables: true,
        breaks: true,
        pedantic: false,
        smartLists: true,
        smartypants: false
    });
    return marked(dompurify.sanitize(txt));
}

function getBrowserLang() {
    return window.navigator.language.slice(0, 2)
}

function getProxyUrl(url, proxy) {
    proxy = proxy || false;
    if (proxy) {
        return proxy + encodeURIComponent(url);
    }
    return url;
}

function getBaseUrl(url) {
    return url.split("?")[0];
}

function parseQueryString(queryString) {
    var params = {};
    var pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
    for (var i = 0; i < pairs.length; i++) {
        var pair = pairs[i].split('=');
        if (pair[1]) {
            params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
        }
    }
    return params;
}

function getQueryString(params) {
    var query_params = [];
    for (var key in params) {
        if (params[key]) {
            query_params.push([key, params[key]].join('='))
        }
    }
    return query_params.join('&');
}

function getUrlParameter(query, param, defaultValue) {
    var response = defaultValue || 0;
    if (query) {
        var value = new URLSearchParams(query).get(param);
        if ((typeof value !== "undefined") && (value !== null)) {
            response = 0 ? (["0", "false"].includes(value)) : value;
        }
    }
    return response;
}

function updateQueryString(querystring, param, value) {
    if (querystring) {
        var params = parseQueryString(querystring);
        if (value !== false) {
            params[param] = value;
        }
        return getQueryString(params);
    }
    return [param, value].join('=');
}

function getUrl(url, params) {
    const queryString = getQueryString(params);
    return [url, queryString].join('?');
}

function checkQueryParam(querystring, paramName, paramValue) {
    const param = getUrlParameter(querystring, paramName);
    if (param != paramValue) {
        return updateQueryString(
            querystring,
            paramName,
            paramValue
        );
    }
    return querystring;
}

function checkQueryParams(querystring, newParams) {
    for (const paramName in newParams) {
        querystring = checkQueryParam(querystring, paramName, newParams[paramName])
    }
    return querystring;
}

// Remove duplicate params
function cleanQueryString(querystring) {
    var params = parseQueryString(querystring);
    return getQueryString(params);
}

function truncate(text, length) {
    var spaceIndex =
        length < text.length ? text.lastIndexOf(" ", length) : -1;
    return spaceIndex !== -1 ?
        text.substring(0, spaceIndex) + "..." :
        text;
}

function join(values, separator) {
    return values.join(separator);
}

function translateValue(value, list, defaultValue) {
    defaultValue = defaultValue || "";
    var item = list.find(v => {
        return v.value == value
    });
    return item ? item.text : defaultValue;
}

function translateArray(values, list, defaultValue) {
    values = values ? values : [];
    return values.map(function(value) {
        return translateValue(value, list, defaultValue);
    });
}

function arrayInArray(values, list) {
    return list.filter(value =>
        values.includes(value.toLowerCase())
    ).length;
}

function isEmptyObject(obj) {
    return Object.keys(obj).length === 0;
}

function cleanArray(arr) {
    if (arr && Array.isArray(arr)) {
        return arr.filter(value => {
            return value && !isEmptyObject(value);
        });
    }
    return arr;
}

function cleanValues(array, field, addEmpty) {
    field = field || false;
    addEmpty = addEmpty || false;
    // Remove empty values
    array = cleanArray(array);
    var unique_values = [];
    // Get unique values
    if (field) {
        var values = []
        for (var i = 0, n = array.length; i < n; i++) {
            const value = converter.getValue(array[i], field)[0];
            if (value && !values.includes(value)) {
                values.push(value);
                unique_values.push(array[i]);
            }
        }
        if (addEmpty) {
            unique_values.push({});
        }
    } else {
        for (var i = 0, n = array.length; i < n; i++) {
            if (!unique_values.includes(array[i])) {
                unique_values.push(array[i]);
            }
        }
        if (addEmpty) {
            unique_values.push("");
        }
    }
    return unique_values;
}

function removeDuplicate(arr) {
    return arr.filter((value, index) => {
        return arr.indexOf(value) == index;
    });
}


function isEmptyArray(arr, clean) {
    if (arr && Array.isArray(arr)) {
        arr = clean ? cleanArray(arr) : arr;
        return arr.filter(value => value).length == 0;
    }
    return arr;
}

function getFile(url, format, config) {
    config = config || {};
    if (format == 'xml') {
        config['headers'] = { "Accept": "application/xml" };
    }
    return axios
        .get(url, config)
        .then(function(response) {
            return response;
        })
        .catch(function(error) {
            return error;
        })
}

function readFile(file, callback) {
    var reader = new FileReader();
    reader.onloadend = (e) => {
        var data = e.target.result;
        callback(data);
    };
    reader.readAsText(file);
}

function formatDate(date, format) {
    date = date instanceof Date ? date : new Date(date);
    format = format || 'YYYY-MM-DD'
    const YYYY = date.getFullYear();
    const YY = YYYY.toString().slice(-2);
    const MM = String(date.getMonth() + 1).padStart(2, '0'); //January is 0!
    const DD = String(date.getDate()).padStart(2, '0');
    const hh = String(date.getHours()).padStart(2, '0');
    const mm = String(date.getMinutes()).padStart(2, '0');
    const ss = String(date.getSeconds()).padStart(2, '0');
    return format
        .replace('YYYY', YYYY)
        .replace('YY', YY)
        .replace('MM', MM)
        .replace('DD', DD)
        .replace('hh', hh)
        .replace('mm', mm)
        .replace('ss', ss);

}

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

function nl2br(str, is_xhtml) {
    if (typeof str === 'undefined' || str === null) {
        return '';
    }
    var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}

function isWxs() {
    return function (linkageProtocol, protocol) {
        if (linkageProtocol) {
            protocols = ['wfs', 'wms'];
            if (protocol) {
                return linkageProtocol.toLowerCase().indexOf(protocol) !== -1;
            } else {
                isProtocol = false;
                for (var i = 0; i < protocols.length; i++) {
                    if (linkageProtocol.toLowerCase().indexOf(protocols[i]) !== -1) {
                        isProtocol = true;
                    }
                }
                return isProtocol;
            }
        }
        return false;
    };
};


export default {
    toHtml: toHtml,
    getProxyUrl: getProxyUrl,
    getBaseUrl: getBaseUrl,
    getUrlParameter: getUrlParameter,
    truncate: truncate,
    join: join,
    translateValue: translateValue,
    translateArray: translateArray,
    arrayInArray: arrayInArray,
    isEmptyObject: isEmptyObject,
    cleanArray: cleanArray,
    cleanValues: cleanValues,
    removeDuplicate: removeDuplicate,
    isEmptyArray: isEmptyArray,
    getFile: getFile,
    readFile: readFile, 
    getUrl: getUrl,
    sleep: sleep,
    getBrowserLang: getBrowserLang,
    parseQueryString: parseQueryString,
    getQueryString: getQueryString,
    updateQueryString: updateQueryString,
    checkQueryParam: checkQueryParam,
    checkQueryParams: checkQueryParams,
    cleanQueryString: cleanQueryString,
    nl2br: nl2br,
    isWxs: isWxs,
    formatDate: formatDate
}