(function () {
    'use strict';

    window._stateSet = function () {
        window._stateSet = function () {
            console.log('Call _stateSet only once');
        };
        let appState = window._appState;

        function getToken(token) {
            fetch('https://gymlink.freemyip.com/api/auth/authorize_client', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    GymKey: token, // Just testing token
                    id: '123',
                }),
            })
                .then(res => res.json())
                .catch(e => {
                    console.log(e);
                    setTimeout(getToken, 1000);
                })
                .then(data => {
                    if (data.payload) appState.checkToken(data.payload.token);
                    else {
                        console.log(data);
                        setTimeout(getToken, 1000);
                    }
                });
        }

        const btn = document.getElementById('token');
        btn.addEventListener('click', () => getToken('eeb42dcb-8e5b-4f21-825a-3fc7ada43445'));

        const btn2 = document.getElementById('token2');
        btn2.addEventListener('click', () => getToken('a8622a61-3142-487e-8db8-b6aebd4f04aa'));

        let colorChangeBtnRed = document.getElementById('colorChangeBtnRed');
        colorChangeBtnRed.addEventListener('click', function () {
            var hexColor = '#FF0000'.substring(1);
            var numColor = parseInt(hexColor, 16);
            appState.changeColor(numColor, true);
        });

        let colorChangeBtnBlue = document.getElementById('colorChangeBtnBlue');
        colorChangeBtnBlue.addEventListener('click', function () {
            var hexColor = '#0000FF'.substring(1);
            var numColor = parseInt(hexColor, 16);
            appState.changeColor(numColor, false);
        });
        let clearBtn = document.getElementById('clearBtn');
        clearBtn.addEventListener('click', function () {
            localStorage.clear();
            window.location.reload();
        });

        function onError() {
            console.error('Error');
        }

        appState.setOnError(onError);
    };
})();
