/**
 * @since Last modified: 2024-07-06 19:34:32
 * @constant bulletinTools
 * @description Collection of operation methods for bulletin.
 * @see {@link https://codepen.io/axui/pen/abXwOXm|demo @ codepen}
 */
'use strict';
import { T_el, T_obj } from "../../../types/ax";
import prefix from "../global/prefix";
import getDataType from "./getDataType";
import getEl from "./getEl";
import getEls from "./getEls";
import isEmpty from "./isEmpty";
import renderTpl from "./renderTpl";
const bulletinTools = {
    /**
     * @memberof bulletinTools
     * @description Determine whether the two nodes contain or equal relationships.
     * @param  {object} [global={}] - Global paramsters.
     * @returns {boolean} Return template string.
     * @see {@link https://codepen.io/axui/pen/bGzQOYP|demo @ codepen}
     * @example
     * ax.bulletinTools.getItemTpl([{cube,label,tips,...}...],{paddingless,multiline,hoverable});
     * <!--return template string-->
     */
    getItemTpl: (global: T_obj = {}): string => {
        return `
        {{let check = this.checked && (!['checkboxes','radios'].includes('${global.type}') && !['checkbox','radio'].includes(this.type)) ?'checked':'',
                value = this.value?'value="'+ this.value +'"':'',
                selected=this.selected?'selected':'',
                active=this.active?'active':'',
                disabled=this.disabled?'disabled':''; 
        /}}
        <${global.childNode}>
                    <div class="${prefix}bulletin" ${global.paddingless ? 'paddingless' : ''} ${global.hoverable ? 'hoverable' : ''}  ${global.multiline ? 'multiline' : ''} {{!['checkboxes','radios'].includes(this.type)? value :''}} {{selected}} {{active}} {{check}}  {{disabled}}>
                    {{this.icon?'<i role="icon" class="'+this.icon+'"></i>':''}}
                    {{this.disk?'<span role="disk"><img src="'+this.disk+'"></span>':''}}
                    {{this.cube?'<span role="cube"><img src="'+this.cube+'"></span>':''}}
                    <div class="${prefix}bulletin-body">
                        {{if('${global.type}' ==='checkboxes' || this.type ==='checkbox'){/}}
                            <ax-checkbox name="{{this.name}}" {{this.checked?'check="ed"':''}} {{value}}>{{this.label}}</ax-checkbox>
                        {{}else if ('${global.type}' ==='radios' || this.type==='radio'){/}}
                            <ax-radio name="{{this.name}}" {{this.checked?'check="ed"':''}} {{value}}>{{this.label}}</ax-radio>
                        {{}else if(this.href){/}}
                            <a role="caption" href="{{this.href}}" {{this.target?'target="'+ this.target +'"':''}} {{this.rel?'rel="'+ this.rel +'"':''}}>{{this.label}}</a>
                        {{}else{/}}
                            <span role="caption">{{this.label}}</span>
                        {{}/}}
                    </div>
                    {{this.badge?'<ax-badge>'+this.badge+'</ax-badge>':''}}
                    {{this.tips?'<i role="tips"><img src="'+this.tips+'"></i>':''}}
                    {{this.arrow?'<i class="'+this.arrow+'" role="arrow"></i>':''}}
                    </div>
                    ${global.divisible ? '<hr>' : ''}
                </${global.childNode}>
        `;
    },
    /**
     * @memberof bulletinTools
     * @description Determine whether the two nodes contain or equal relationships.
     * @param  {object} [global={}] - Global paramsters.
     * @returns {boolean} Return template string.
     * @see {@link https://codepen.io/axui/pen/bGzQOYP|demo @ codepen}
     * @example
     * ax.bulletinTools.getListTpl([{cube,label,tips,...}...],{paddingless,multiline,hoverable});
     * <!--return template string-->
     */
    getListTpl: function(global: T_obj = {}): string  {
        let grid = '';
        if (global.cols > 0) {
            grid = `${prefix}grid  ${prefix}avg-${global.cols}`;
            grid += global.lines==='fence' ? ` ${prefix}fence` :global.lines==='fluid' ? ` ${prefix}fluid` : '';
        }
        return `
        <${global.parentNode} class="${prefix}reset ${grid}">
            {{for(let k of this){/}}
                ${this.getItemTpl(global).replaceAll('this.','k.')}
            {{}/}}
        </${global.parentNode}>`;
    },
    getChildNodes: (data: any) => {
        let result = [];
        if (isEmpty(data)) { return []; }
        let dataType = getDataType(data);
        if (dataType.includes('HTML')) {
            result = getEls(`.${prefix}bulletin`, data);
        } else if (dataType === 'Array') {
            if (data[0]?.el) {
                result = data.map((k: any) => k.el);
            } else {
                result = data;
            }
        }
        return result;
    },
    getVals: function (data: any) {
        let result: string[] = [];
        if (isEmpty(data)) { return ''; }
        let els = this.getChildNodes(data);
        if (els.length > 0) {
            if (els[0].querySelector('input')) {
                els.forEach((k: any) => {
                    let input = k.querySelector('input');
                    input.checked && result.push(input.value);
                });
            } else {
                els.forEach((k: any) => {
                    k.hasAttribute('checked') && result.push(k.getAttribute('value'));
                });
            }
        }
        return result.filter(Boolean).join(',');
    },
    preset: function (vals: string[] | string, els: any) {
        let dataType = getDataType(vals);
        let values: string[] = [],
            elems = this.getChildNodes(els);
        if (dataType === 'Array') {
            values = vals as string[];
        } else if (dataType === 'String') {
            values = (vals as string).split(',').filter(Boolean);
        }
        if (elems.length === 0) { return false }
        if (values.length === 0) {
            elems.forEach((k: any) => {
                let input = k.querySelector('AX-CHECKBOX,AX-RADIO')
                input ? input.removeAttribute('check') : k.removeAttribute('checked');
            });
        } else {
            let checkedItems = values.map((k: any) => elems.find((i: any) => i?.querySelector('input')?.value == k || i.getAttribute('value') == k)).filter(Boolean);
            elems.forEach((k: any) => {
                let input = k.querySelector('AX-CHECKBOX,AX-RADIO')
                if (checkedItems.includes(k)) {
                    input ? input.setAttribute('check', 'ed') : k.setAttribute('checked', '');
                } else {
                    input ? input.removeAttribute('check') : k.removeAttribute('checked');
                }
            });
        }
    },
    toggleChecked: (item: T_el, els: T_el[], type = 'single-select') => {
        if (!item) { return false; }
        let checked = item.hasAttribute('checked');
        if (type === 'single-select') {
            if (checked) {
                return false;
            } else {
                item.setAttribute('checked', '');
                els.filter((k: any) => k !== item && item.hasAttribute('checked')).forEach((k: any) => {
                    k.removeAttribute('checked');
                });
            }
        } else {
            checked ? item.removeAttribute('checked') : item.setAttribute('checked', '');
        }
    },
    fillTarget: (target: T_el, vals: string) => {
        let el = getEl(target);
        if (!el) { return false }
        let nodeName = el.nodeName;
        if (['AX-INPUT', 'AX-TEXTAREA'].includes(nodeName)) {
            el.setAttribute('value', vals);
        } else if (['INPUT', 'TEXTAREA'].includes(nodeName)) {
            el.value = vals;
        } else {
            el.innerHTML = vals;
        }
    },
    cancelChecked: (els: T_el[]) => {
        if (isEmpty(els)) { return false }
        els.forEach((k: any) => {
            let input = k.querySelector('AX-CHECKBOX,AX-RADIO');
            if (input) {
                input.removeAttribute('check');
            } else {
                k.removeAttribute('checked');
            }
        });
    },
}
export default bulletinTools;
