export const createElement = (template: string): HTMLElement => {
    const outer: HTMLElement = document.createElement(`DIV`);
    outer.className = `wrapper`;
    outer.innerHTML = template;
    return outer;
};

export const toggleOverlay = (show: boolean): void => {
    const body = document.querySelector(`body`);

    if (show) {
        const overlay = document.createElement(`DIV`);
        overlay.className = `overlay`;
        overlay.id = `overlay`;
        body.appendChild(overlay);
    } else {
        const overlay = document.querySelector(`#overlay`);

        if (overlay) {
            overlay.remove();
        }
    }
};

interface UrlVars {
    [name: string]: string
}

/**
 * Метод, возвращающий объект с хешами
 * @returns {UrlVars}
 */
export const getUrlVars = (): UrlVars => {
    const vars: UrlVars = {};
    location.hash.replace(/[#&]+([^=&]+)=([^&]*)/gi, (m: any, key: string, value: string): any => {
        vars[key] = value;
    });

    return vars;
};

/**
 * Метод для поиска нужного родителя по переданному классу
 * @param {HTMLElement} element
 * @param {string} cls
 * @returns {HTMLElement}
 */
export const findAncestor = (element: HTMLElement, cls: string) => {
    while ((element = element.parentElement) && !element.classList.contains(cls));
    return element;
};

export enum KeyCode {
    ENTER = 13,
    ESC = 27
}

export enum TypeFields {
    NUMBER = 1,
    DATE = 2,
    TEXT = 3,
    SELECT = 4,
    LINK = 5,
    FILE = 6,
    USER_SELECT = 7,
    IMAGE = 9,
    GROUP_SELECT = 14
}

export const URL = `${location.origin + location.pathname}`;

export const hideElem = (elem: any) => {
    elem.classList.add(`hidden`);
};

export const showElem = (elem: any) => {
    elem.classList.remove(`hidden`);
};

export const drawNoAccess = (text: string): string => {
    return `<span class="cb-no-access">${text}</span>
<div class="cb-no-access-btn-wrap">
  <button type="button" id="back-btn" class="nav-bar__btn nav-bar__btn--back">Вернуться в таблицу</button>
</div>`;
};

export const renderPage = (obj: any): void => {
    const wrap = document.querySelector(`#app`);
    if (wrap) {
        wrap.appendChild(obj.render());
    }
}