// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkID=397704
// To debug code on page load in cordova-simulate or on Android devices/emulators: launch your app, set breakpoints, 
// and then run "window.location.reload()" in the JavaScript Console.
(function () {
    "use strict";

    var _Root;
    var _RootAlt;
    var _ImageZero;
    var _JsonTimer;
    var _ImageTimer;
    var _DataDirectory;

    var _Pause = 0;
    var _Images = [];
    var _JsonInterval;
    var _ImageInterval;
    var _ImageIndex = 0;
    var _OpaqueIndex = 0;
    var _DeviceReadyDiv = $("#deviceReady div");

    $(document).ready(function () {

        console.log("onDeviceReady");

        // Handle the Cordova pause and resume events
        document.addEventListener('pause', onPause.bind(this), false);
        document.addEventListener('resume', onResume.bind(this), false);

        document.addEventListener('keyup', getInput, false);

        var url = '../slideshow/index.json';
        console.log(url);
        var _ = $.getJSON(url, function (data) {
            console.log(url + " downloaded successfully");
            _RootAlt = null;
            _Root = data.Root;
            _ImageZero = data.ImageZero;
            _JsonInterval = data.JsonInterval;
            _ImageInterval = data.ImageInterval;
            _DataDirectory = data.DataDirectory;
            console.log(url + " used successfully");
        })
            .done(function () {
                loadData();

                _JsonTimer = setInterval(onTickJSON, _JsonInterval);
                _ImageTimer = setInterval(onTickImage, _ImageInterval);
            })
            .fail(function (er) {
                console.log("error", er);
                _ImageInterval = 5000;
                _JsonInterval = 59000;
                _Root = "../pictures";
                _DataDirectory = "../random";
                // _ImageZero = "images/img_tree.gif";
                // _ImageZero = "images/output-onlinepngtools.png";
                _ImageZero = "images/1x1_00000000.png"; // https://shoonia.github.io/1x1/#00000000
            })
            .always(function () {
                console.log("complete");
            });
    });

    function onPause() {
        // TODO: This application has been suspended. Save application state here.
    }

    function onResume() {
        // TODO: This application has been reactivated. Restore application state here.
    }

    function goBack() {
        _Pause = 1;
        if (_Pause === 0) {
            _ImageIndex -= 1;
        }
        else {
            _ImageIndex -= 2;
        }
        if (_ImageIndex === 0) {
            _ImageIndex = _Images.length - 1;
        }
        var backgroundImage = GetBackgroundImage();
        _DeviceReadyDiv.attr('style', backgroundImage);
    }

    function goForward() {
        _Pause = 1;
        _ImageIndex += 1;
        if (_ImageIndex >= _Images.length) {
            _ImageIndex = 0;
        }
        var backgroundImage = GetBackgroundImage();
        _DeviceReadyDiv.attr('style', backgroundImage);
    }

    function changeImageTimer(imageInterval) {
        _ImageInterval = imageInterval;
        clearTimeout(_ImageTimer);
        _ImageTimer = setInterval(onTickImage, _ImageInterval);
    }

    function getInput(e) {
        var which = e.which;
        switch (which) {
            case 13: //Okay
                if (_Pause === 0) {
                    _Pause = 1;
                }
                else {
                    _Pause = 0;
                }
                break;
            case 37: //Left
                goBack();
                break;
            case 38: //Up
                goForward();
                break;
            case 39: //Right
                goForward();
                break;
            case 40: //Down
                goBack();
                break;
            case 173: //Fast Forward
                goForward();
                break;
            case 177: //Rewind
                goBack();
                break;
            case 8: //Delete
                console.log('Delete key was pressed!');
                break;
            case 48: //0
                changeImageTimer(10000);
                break;
            case 49: //1
                changeImageTimer(1000);
                break;
            case 50: //2
                changeImageTimer(2000);
                break;
            case 51: //3
                changeImageTimer(3000);
                break;
            case 52: //4
                changeImageTimer(4000);
                break;
            case 53: //5
                changeImageTimer(5000);
                break;
            case 54: //6
                changeImageTimer(6000);
                break;
            case 55: //7
                changeImageTimer(7000);
                break;
            case 56: //8
                changeImageTimer(8000);
                break;
            case 57: //9
                changeImageTimer(9000);
                break;
            default:
        }
    }

    function loadData() {
        var currentDate = new Date();
        var mm = (new Date().getMonth() + 1).toString().padStart(2, '0');
        var dd = currentDate.getDate().toString().padStart(2, '0');
        var url = _DataDirectory + '/' + mm + '-' + dd + '.json';
        console.log(url);
        var _ = $.getJSON(url, function (data) {
            console.log("success", data.length);
            _Images = [];
            $.each(data, function (index, value) {
                _Images.push(value.replaceAll("\\", "/"));
            });
        })
            .done(function () {
                console.log("second success");
            })
            .fail(function (er) {
                console.log("error", er);
                _Images = [_ImageZero];
            })
            .always(function () {
                console.log("complete");
            });
    }

    function onTickJSON() {
        var currentDate = new Date();
        var currentHours = currentDate.getHours();
        if (currentHours === 21) {
            var currentMinutes = currentDate.getMinutes();
            if (currentMinutes === 0) {
                loadData();
            }
        }
    }

    function GetBackgroundImage() {
        var result = "background-image: url('" + _Root + _Images[_ImageIndex] + "'), url('";
        if (_RootAlt !== null) {
            result = result + _RootAlt + _Images[_ImageIndex] + "'), url('";
        }
        result = result + _ImageZero + "');";
        return result;
    }

    function onTickImage() {
        if (_Images.length > 0 && _Pause === 0) {
            var currentDate = new Date();
            var currentHours = currentDate.getHours();
            if (currentHours >= 22 || currentHours <= 6) {
                _DeviceReadyDiv.attr('style', 'background-color: #191717;');
            }
            else {
                _DeviceReadyDiv.eq(_OpaqueIndex).removeClass("opaque");
                _ImageIndex += 1;
                if (_ImageIndex >= _Images.length) {
                    _ImageIndex = 0;
                }
                var loadIndex;
                switch (_OpaqueIndex) {
                    case 0:
                        loadIndex = 2;
                        _OpaqueIndex = 1;
                        break;
                    case 1:
                        loadIndex = 0;
                        _OpaqueIndex = 2;
                        break;
                    case 2:
                        loadIndex = 1;
                        _OpaqueIndex = 0;
                        break;
                    default:
                }
                var backgroundImage = GetBackgroundImage();
                _DeviceReadyDiv.eq(loadIndex).attr('style', backgroundImage);
                _DeviceReadyDiv.eq(_OpaqueIndex).addClass("opaque");
            }
        }
    }

})();