// "com.vqvelocity.sdappcontrol.sortby.dateJoined": "dateJoined",
// "com.vqvelocity.sdappcontrol.sortby.points": "points",
// "com.vqvelocity.sdappcontrol.sortby.numberOfWorkouts": "numberOfWorkouts",
// "com.vqvelocity.sdappcontrol.sortby.name": "name"
class SortByEventHandler extends SDEventHandler {

    handleStreamDeckEvent = (message) => {
        console.log("SortByEventHandler.handleStreamDeckEvent", message);
        if (message.event === "sortBy") {
            this._sortBy(message.sortAlg);
        }
    }

    _tryClickSortByButton = (sortAlg, attempts) => {
        return new Promise((resolve) => {
            if (attempts <= 0) {
                throw new ControlsNotFoundError(`Could not find button for Sort Toggling by ${sortAlg}!`);
            }
            console.log(`Trying to find button for Sort Toggling by ${sortAlg}!`);
            // let button = document.querySelector(`button[jsname="vnVdbf"][data-emoji^="${sortAlg}"]`);
            // const toggleSelector = `[jscontroller="soHxf"][data-panel-id="${sidepanelTabId}"]`;
            const toggleSelector = `[jscontroller="sortby_${sortAlg}"]`;
            let button = document.querySelector(toggleSelector);

            if (button) {
                button.click();
                resolve(true);
            } else {
                resolve(new Promise((resolve) => setTimeout(() => {
                    resolve(this._tryClickSortByButton(sortAlg, attempts - 1));
                }, 300)));
            }
        });
    }

    _sortBy = (sortAlg) => {
        console.log(`SortByEventHandler._sortBy(${sortAlg})`);
        this._tryClickSortByButton(sortAlg, 1).catch(() => {
            this._tryClickSortByButton(sortAlg, 5);
        });
    }
}