// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.

define(['hp/core/Localizer',
    'hp/core/Style',
    'text!hpPages/core/hp_select_date_range.html',
    'jquery'],
function(localizer, style, dateRangeHtml) {
"use strict";

    (function($) {
        // jQuery plugin definition

        $.fn.hpSelectDateRange = function(action, args) {
          
            var MILLISECONDS_PER_WEEK = (1000 * 60 * 60 * 24 * 7);
            var SELECT_ID_FORMAT =
                new RegExp('\\[(\\d{4}-\\d{2}-\\d{2}) TO (\\d{4}-\\d{2}-\\d{2})\\]');

            function hpSelectDateRange(elem) {

                var hpSelect;
                var toDate = new Date();
                toDate.setHours(0, 0, 0, 0);
                var fromDate = new Date(toDate.getTime() - MILLISECONDS_PER_WEEK);
                
                function parseDate(date) {
                    // convert 'yyyy-mm-dd' to Date object
                    return new Date(
                        parseInt(date.slice(0,4), 10),
                        parseInt(date.slice(5,7), 10) - 1,
                        parseInt(date.slice(8,10), 10));
                }
                
                function parseSelectId(id) {
                    var result = false;
                    var matches = SELECT_ID_FORMAT.exec(id);
                    if (matches && matches.index >= 0) {
                        fromDate = parseDate(matches[1]);
                        toDate = parseDate(matches[2]);
                        result = true;
                    }
                    return result;
                }
                
                function formatSelectId() {
                    return '[' + $.datepicker.formatDate('yy-mm-dd', fromDate) +
                        ' TO ' + $.datepicker.formatDate('yy-mm-dd', toDate) + ']';
                }
                
                function setSelect() {
                    var id = formatSelectId();
                    $('li.hp-select-date-range', hpSelect).attr('data-id', id);
                    hpSelect.hpSelect('set', id);
                }
                
                function onSelectFromDate(date) {
                    fromDate = parseDate(date);
                    // don't let fromDate be later than toDate
                    if (fromDate.getTime() > toDate.getTime()) {
                        toDate = fromDate;
                        $('.hp-date-range-to', hpSelect).datepicker('setDate', toDate);
                    }
                    setSelect();
                }
                
                function onSelectToDate(date) {
                    toDate = parseDate(date);
                    // don't let toDate be earlier than fromDate
                    if (toDate.getTime() < fromDate.getTime()) {
                        fromDate = toDate;
                        $('.hp-date-range-from', hpSelect).datepicker('setDate', fromDate);
                    }
                    setSelect();
                }
                
                function onSelectChange() {
                    var id = $('.hp-select-date-range', hpSelect).attr('data-id');
                    if (id) {
                        if (parseSelectId(id)) {
                            // select changed, probably due to a browser history, paste, or reload
                            // update dates from what was set
                            $('.hp-date-range-from', hpSelect).datepicker('setDate', fromDate);
                            $('.hp-date-range-to', hpSelect).datepicker('setDate', toDate);
                        }
                    }
                }
                
                function onClickOption() {
                    $('.hp-date-range', hpSelect).show();
                    // scroll to show it
                    var container = $('.hp-options', hpSelect);
                    container.scrollTop(container[0].scrollHeight);
                    $('.hp-date-range-from').focus();
                }
                
                function swallowEvent(ev) {
                    ev.stopPropagation();
                }

                function build() {
                    if ($('.hp-date-range', hpSelect).length === 0) {
                        var dateRangeElements = $(dateRangeHtml);
                        localizer.localizeDom(dateRangeElements);
                        $('.hp-options', hpSelect).append(dateRangeElements);
                    }
                }

                function initialize() {
                    hpSelect = $(elem);

                    if ('destroy' !== action) {
                        if (! action || 'object' === typeof(action)) {
                            args = action;
                            action = 'initialize';
                        }

                        if ('initialize' === action) {
                            build();
                            
                            var id = formatSelectId();
                            $('li.hp-select-date-range', hpSelect).attr('data-id', id);
                            
                            hpSelect.on('click.hpSelectDateRange',
                                '.hp-select-date-range', onClickOption);
                            hpSelect.on('change.hpSelectDateRange', onSelectChange);
                            $('.hp-date-range-from', hpSelect).datepicker({
                                dateFormat: 'yy-mm-dd',
                                onSelect: onSelectFromDate,
                                defaultDate: fromDate
                            });
                            $('.hp-date-range-to', hpSelect).datepicker({
                                dateFormat: 'yy-mm-dd',
                                onSelect: onSelectToDate,
                                defaultDate: toDate
                            });
                            $('.hp-date-range', hpSelect).on('change.hpSelectDateRange',
                                swallowEvent);
                        }
                    } else {
                        hpSelect.off('.hpSelectDateRange');
                    }
                }

                initialize();
            }

            // pluginify
            var ret, instance;
            this.each(function() {
                var $elem = $(this);
                instance = new hpSelectDateRange($elem[0]);
                ret = ret ? ret.add($elem) : $elem;
            });
            return ret;
        };
    }(jQuery));
});
