import { Controller } from '@hotwired/stimulus';

/**
 * Show / hide items in left-hand menu
 * [template: data_entry.html.twig]
 * @todo Handle open / closed state
 */
export default class extends Controller {
    static targets = [
        'vocabs',
        'records',
        'vocabIcon',
        'recordIcon'
    ];
    static values = {
        state: Number,
    };

    initialize() {
        const recordsClass = localStorage.getItem('recordsClass');
        const vocabsClass = localStorage.getItem('vocabsClass');
        if (recordsClass) {
            this.recordsTarget.className = recordsClass;
            this.recordIconTarget.className = recordsClass.includes('hidden') ?
                this.closeIcon(this.recordIconTarget) :
                this.openIcon(this.recordIconTarget);
        }
        if (vocabsClass) {
            this.vocabsTarget.className = vocabsClass;
            this.vocabIconTarget.className = vocabsClass.includes('hidden') ?
                this.closeIcon(this.vocabIconTarget) :
                this.openIcon(this.vocabIconTarget);
        }
    }

    toggle(event) {
        if (event.currentTarget.id === 'for-vocabs') {
            this.vocabsTarget.classList.toggle('is-hidden');
            localStorage.setItem('vocabsClass', this.vocabsTarget.className);
        }

        if (event.currentTarget.id === 'for-records') {
            this.recordsTarget.classList.toggle('is-hidden');
            localStorage.setItem('recordsClass', this.recordsTarget.className);
        }

        this.changeIcon(event.currentTarget.firstElementChild);
    }

    changeIcon(icon) {
        const iconState = icon.className.includes('right') ? 'right' : 'down';

        const iconAction = {
            'right': function() {
                icon.className = icon.className.replace('right', 'down');
            },
            'down': function() {
                icon.className = icon.className.replace('down', 'right');
            }
        };

        iconAction[iconState]();

        this.iconClass = icon.className;        
    }

    openIcon(icon) {
        return icon.className.replace('right', 'down');
    }

    closeIcon(icon) {
        return icon.className.replace('down', 'right');
    }
}
