// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
define(['hp/core/Localizer',
    'hp/model/DevelopmentSettings',
    'jquery',
    'hp/lib/date',
    'lib/jquery.dateFormat',
    'hp/lib/interval'],
function (localizer, settings) {
"use strict";
    (function ($) {
        // For updating hpTimestamp on page at date change
        var lastDateStamp;
        // jQuery plugin definition
        $.fn.hpTimestamp = function (arg) {
          
            var MILLISECONDS_PER_DAY = (1000 * 60 * 60 * 24);
            var ret;
            
            function formatInterval(interval) {
                var days = (interval.years * 365) + interval.days;
                var result;
                
                if (days) {
                    result = localizer.getString('core.duration.dh',
                        [days, interval.hours, interval.minutes, interval.seconds]);
                } else if (interval.hours) {
                    result = localizer.getString('core.duration.hm',
                        [interval.hours, interval.minutes, interval.seconds]);
                } else if (interval.minutes) {
                    result = localizer.getString('core.duration.ms',
                        [interval.minutes, interval.seconds]);
                } else {
                    result = localizer.getString('core.duration.s', [interval.seconds]);
                }
                
                return result;
            }
            
            function formatTime(date) {
                var today = new Date();
                today.setHours(0, 0, 0, 0);
                var endOfToday = today.getTime() + MILLISECONDS_PER_DAY;
                var endOfTomorrow = endOfToday + MILLISECONDS_PER_DAY;
                var yesterday = new Date(today.getTime() - MILLISECONDS_PER_DAY);
                var result;
                
                if (date.getTime() > endOfTomorrow) {
                    result = $.format.date(date, 
                            localizer.getString('core.date.absoluteFormat'));
                } else if (date.getTime() > endOfToday) {
                    result = localizer.getString('core.date.tomorrow',
                            [$.format.date(date,
                                localizer.getString('core.date.tomorrowFormat'))]);
                } else if (date.getTime() > today.getTime()) {
                    result = localizer.getString('core.date.today',
                        [$.format.date(date,
                            localizer.getString('core.date.todayFormat'))]);
                } else if (date.getTime() > yesterday.getTime()) {
                     result = localizer.getString('core.date.yesterday',
                        [$.format.date(date,
                            localizer.getString('core.date.yesterdayFormat'))]);
                } else if (date.getFullYear() >= today.getFullYear()) {
                    result = $.format.date(date,
                        localizer.getString('core.date.thisYearFormat'));
                } else {
                    result = $.format.date(date,
                        localizer.getString('core.date.priorYearFormat'));
                }
                
                return result;
            }
            
            function updateElement(elem, date, endDate, interval) {
                if (endDate && !isNaN(endDate.getTime())) {
                    elem.attr('date-timestamp', date.toISOString() + '/' +
                        endDate.toISOString());
                } else if (interval) {
                    elem.attr('date-timestamp', date.toISOString() + '/' +
                        interval.toISODuration());
                } else {
                    elem.attr('date-timestamp', date.toISOString());
                }
            
                if (endDate || interval) {
                    elem.text(formatInterval(interval));
                } else {
                    elem.text(formatTime(date));
                }
            }
            
            function transform(original, elem) {
                var elements = original.split('/');
                var date = Date.parseISOString(elements[0]);
                var endDate, interval;
                
                if (elements.length > 1) {
                    // this is an interval
                    if (elements[1][0] === "P") {
                        // ISO 8601 duration format
                        // sonar requires reference to window. 
                        interval = window.Interval.parseISODuration(elements[1]);
                    } else {
                        endDate = Date.parseISOString(elements[1]);
                        if (!isNaN(date.getTime()) &&
                            !isNaN(endDate.getTime())) {
                            interval = window.Interval.between(date, endDate);
                        }
                    }
                }
                
                if (!isNaN(date.getTime())) {
                    updateElement(elem, date, endDate, interval);
                }
            }
            
            // Update hpTimestamp on screen if date has changed
            // i.e. 'Today' after midnight should be 'Yesterday'
            function setUpdateTimestampTimer() {
            	lastDateStamp = (new Date()).setHours(0,0,0,0); // milliseconds
                setInterval(function(){
                    var today = (new Date()).setHours(0,0,0,0); // milliseconds
                    if (today !== lastDateStamp) { // The user may set the time forward or backward
                        lastDateStamp = today;
                        // Look for all elements with date-timestamp attribute and update them
                        var elements = $('[date-timestamp]:not(.hp-duration)');
                        var length = elements.length;
                        for (var i=0; i<length; i++) {
                            var element = $(elements[i]);
                            transform(element.attr('date-timestamp'), element);
                        }
                    }}, settings.getRefreshInterval());
            }

            this.each(function() {
                var elem = $(this);
                var original;
                
                if (! arg) {
                    // no date given, use element contents
                    // see if we've already built this before
                    if (elem.attr('date-timestamp')) {
                        original = elem.attr('date-timestamp');
                    } else {
                        // use element text
                        original = $(elem).text();
                    }
                } else if ('string' === typeof(arg)) {
                    original = arg;
                }

                if (original) {
                    transform(original, elem);
                }

                ret = ret ? ret.add(elem) : elem;
            });

            // Only setup the timer once, or after browser clear cache
            if (!lastDateStamp) {
                setUpdateTimestampTimer();
            }
            return ret;
        };
    }(jQuery));
});
