import labelCollapseBranch from '@salesforce/label/LightningPrimitiveCellTree.collapseBranch';
import labelExpandBranch from '@salesforce/label/LightningPrimitiveCellTree.expandBranch';
import { LightningElement, api, track } from 'lwc';
import { classSet } from 'lightning/utils';
import { normalizeBoolean, ArraySlice } from 'lightning/utilsPrivate';

const i18n = {
    collapseBranch: labelCollapseBranch,
    expandBranch: labelExpandBranch,
};

export default class PrivateTreeGridCellToggle extends LightningElement {
    @api rowKeyValue;
    @api colKeyValue;
    @api value;

    @track
    state = {
        expanded: false,
        hasChildren: false,
    };

    @track _tabindex = 0;

    get computedButtonClass() {
        return classSet('slds-button slds-button_icon slds-m-right_x-small')
            .add({
                'slds-is-disabled': !this.hasChildren,
            })
            .toString();
    }

    @api
    get tabIndex() {
        return -1;
    }

    set tabIndex(newValue) {
        this.setAttribute('tabindex', newValue);
        this._tabindex = newValue;
    }

    get buttonTabIndex() {
        return this._tabindex;
    }

    @api
    get hasChildren() {
        return this.state.hasChildren;
    }

    set hasChildren(value) {
        this.state.hasChildren = normalizeBoolean(value);
    }

    @api
    get isExpanded() {
        return this.state.expanded;
    }

    set isExpanded(value) {
        this.state.expanded = normalizeBoolean(value);
    }

    get buttonTitle() {
        if (this.isExpanded) {
            return this.formatString(i18n.collapseBranch, this.value);
        }
        return this.formatString(i18n.expandBranch, this.value);
    }

    formatString(str) {
        const args = ArraySlice.call(arguments, 1);

        if (str) {
            return str.replace(/{(\d+)}/g, (match, i) => {
                return typeof args[i] !== 'undefined' ? args[i] : match;
            });
        }
        return '';
    }

    handleChevronClick() {
        const customEvent = new CustomEvent('privatetogglecell', {
            bubbles: true,
            composed: true,
            cancelable: true,
            detail: {
                name: this.rowKeyValue,
                nextState: this.isExpanded ? false : true, // True = expanded, False = collapsed
            },
        });
        this.dispatchEvent(customEvent);
    }

    @api
    focus() {
        this.template.querySelector('button').focus();
    }
}
