(function () {
    'use strict';

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

        function getToken() {
            fetch(
                'http://gymlink.freemyip.com:8080/api/auth/authorize_client',
                {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        GymKey: 'eeb42dcb-8e5b-4f21-825a-3fc7ada43445', // Just testing token
                        id: '123',
                    }),
                }
            )
                .then(res => res.json())
                .catch(e => {
                    console.log(e);
                    setTimeout(getToken, 1000);
                })
                .then(data => {
                    if (data.payload)
                        appState.onTokenReceived(data.payload.token);
                    else {
                        console.log(data);
                        setTimeout(getToken, 1000);
                    }
                });
        }

        let btn = document.getElementById('token');
        btn.addEventListener('click', getToken);

        let colorChangeBtnRed = document.getElementById('colorChangeBtnRed');
        colorChangeBtnRed.addEventListener('click', function () {
            var hexColor = '#FF0000'
                .replace(
                    /^#?([a-f\d])([a-f\d])([a-f\d])$/i,
                    (m, r, g, b) => '#ff' + r + r + g + g + b + b
                )
                .substring(1);
            var numColor = parseInt(hexColor, 16);
            appState.changeColor(numColor);
        });

        let colorChangeBtnBlue = document.getElementById('colorChangeBtnBlue');
        colorChangeBtnBlue.addEventListener('click', function () {
            var hexColor = '#0000FF'
                .replace(
                    /^#?([a-f\d])([a-f\d])([a-f\d])$/i,
                    (m, r, g, b) => '#ff' + r + r + g + g + b + b
                )
                .substring(1);
            var numColor = parseInt(hexColor, 16);
            appState.changeColor(numColor);
        });

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

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