//
//  countDown.js
//
//  Created by Rebecca Stankus on 07/02/18
//  Copyright 2018 High Fidelity, Inc.
//
//  Distributed under the Apache License, Version 2.0.
//  See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html


(function () {
    var _this;

    var ONE_THOUSAND = 1000;
    var HOURS_PER_DAY = 24;
    var TWO_DIGITS = 10;
    var AM_HOURS = 12;
    var PST_TIME_DIFFERENCE = 16;

    var Countdown = function() {
        _this = this;
    };

    Countdown.prototype = {
        interval: null,

        preload: function(entityID) {
            _this.entityID = entityID;
            _this.synchronize();
            _this.interval = Script.setInterval(function() {
                _this.synchronize();
            }, ONE_THOUSAND);
        },

        synchronize: function() {
            var date = new Date();
            var period = "am";
            var hours = date.getHours() - PST_TIME_DIFFERENCE;
            hours = (hours < 0) ? hours + HOURS_PER_DAY : hours;
            if (hours >= AM_HOURS) {
                period = "pm";
                if (hours !== AM_HOURS) {
                    hours -= AM_HOURS;
                }
            }
            hours = hours < TWO_DIGITS ? "0" + hours : hours;
            var minutes = date.getMinutes();
            minutes = minutes < TWO_DIGITS ? "0" + minutes : minutes;
            Entities.editEntity(_this.entityID, { text: hours + ":" + minutes + period});
        },

        unload: function() {
            if (_this.interval) {
                Script.clearInterval(_this.interval);
            }
        }
    };

    return new Countdown;

});