"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.UIDatePicker = void 0;
var aurelia_i18n_1 = require("aurelia-i18n");
var aurelia_event_aggregator_1 = require("aurelia-event-aggregator");
var constants_1 = require("./../../constants/constants");
var ui_internal_1 = require("./../../utils/ui-internal");
var aurelia_framework_1 = require("aurelia-framework");
var ui_format_1 = require("../../utils/ui-format");
var calendar_head_1 = require("./calendar-head");
var calendar_utils_1 = require("./calendar-utils");
var days_page_1 = require("./days-page");
var months_page_1 = require("./months-page");
var time_page_1 = require("./time-page");
var years_page_1 = require("./years-page");
var moment_1 = __importDefault(require("moment"));
var date_utils_1 = require("../../utils/date-utils");
var config_1 = require("../../config");
var base_input_1 = require("./../forms/base-input");
var UIDatePicker = exports.UIDatePicker = (function (_super) {
    __extends(UIDatePicker, _super);
    function UIDatePicker(element, i18n, eventAggregator, dateUtils, bindingEngine, taskQueue, config) {
        var _this = _super.call(this, element) || this;
        _this.i18n = i18n;
        _this.eventAggregator = eventAggregator;
        _this.dateUtils = dateUtils;
        _this.bindingEngine = bindingEngine;
        _this.taskQueue = taskQueue;
        _this.config = config;
        _this.dateOnly = false;
        _this.attachToViewport = true;
        _this.closeOnSelect = true;
        _this.yearOnly = false;
        _this.monthOnly = false;
        _this.onChange = function () { };
        _this.presets = [];
        _this.selectedPreset = null;
        _this.autosetWhenOpened = true;
        _this.initDateWhenOpened = function () { };
        _this.placeholder = "";
        _this.timeOnly = false;
        _this.startHour = 0;
        _this.endHour = 23;
        _this.hourInterval = 1;
        _this.startMinute = 0;
        _this.endMinute = 59;
        _this.minuteInterval = 5;
        _this.translations = constants_1.Internationalization.datePickerTranslationsEN;
        _this.currentPage = calendar_utils_1.CALENDAR_VIEWS.DAYS;
        _this.month = (0, moment_1.default)().startOf("month").toDate();
        _this.VIEWS = calendar_utils_1.CALENDAR_VIEWS;
        element.focus = function () { return _this.inputElement.focus(); };
        _this.disposables = new Array();
        _this.displayWeek = _this.config.globalConfig.displayWeekPicker;
        return _this;
    }
    UIDatePicker.prototype.bind = function () {
        var _this = this;
        _super.prototype.bind.call(this);
        if (this.inputFormat == null) {
            this.initFormat();
        }
        this.changeLanguageSubscription = this.eventAggregator.subscribe(ui_internal_1.UIInternal.EVT_CHANGE_LANGUAGE, function () {
            _this.changeLanguage();
        });
        this.changeLanguage();
        this.dateLabel = ui_format_1.UIFormat.datetime(this.date, this.format);
        if (this.selectedPreset != null) {
            this.date = new Date(this.selectedPreset.preset);
        }
        this.dateChanged(this.date, null);
        this.disposables.push(this.bindingEngine.propertyObserver(this, "selectedPreset").subscribe(function () {
            if (_this.selectedPreset != null) {
                _this.date = new Date(_this.selectedPreset.preset);
            }
        }));
    };
    UIDatePicker.prototype.unbind = function () {
        this.changeLanguageSubscription.dispose();
    };
    UIDatePicker.prototype.initFormat = function () {
        var _a, _b, _c, _d, _e;
        if (this.format != null) {
            this.inputFormat = this.format.toLocaleLowerCase();
        }
        else {
            if (this.dateOnly) {
                this.inputFormat = "dd/mm/yyyy";
                (_a = this.format) !== null && _a !== void 0 ? _a : (this.format = "DD/MM/yyyy");
            }
            else if (this.timeOnly) {
                this.inputFormat = "HH:MM";
                (_b = this.format) !== null && _b !== void 0 ? _b : (this.format = "HH:mm");
            }
            else if (this.monthOnly) {
                this.inputFormat = "mm/yyyy";
                (_c = this.format) !== null && _c !== void 0 ? _c : (this.format = "MM/yyyy");
            }
            else if (this.yearOnly) {
                this.inputFormat = "yyyy";
                (_d = this.format) !== null && _d !== void 0 ? _d : (this.format = "yyyy");
            }
            else {
                this.inputFormat = "dd/mm/yyyy HH:MM";
                (_e = this.format) !== null && _e !== void 0 ? _e : (this.format = "DD/MM/yyyy HH:mm");
            }
        }
    };
    UIDatePicker.prototype.clearSelectionListener = function () {
        this.clearSelection();
    };
    UIDatePicker.prototype.changeListener = function () {
        var _this = this;
        if (this.dateLabel == null || this.dateLabel == '') {
            this.date = null;
        }
        else {
            this.errors = [];
            var m = (0, moment_1.default)(this.dateLabel, this.format);
            if (this.dateUtils.isValid(m)) {
                this.updateDate(m.toDate(), m.toDate());
            }
            else {
                this.errors.push(this.i18n.tr("validation.invalidDate", { ns: "common" }));
                this.date = null;
            }
        }
        this.taskQueue.queueMicroTask(function () {
            _this.onChange({ date: _this.date });
        });
    };
    UIDatePicker.prototype.attached = function () {
        var _this = this;
        if (this.allowClear) {
            this.inputElement.allowClear = true;
            this.inputElement.element.addEventListener("clear", function () { return _this.clearSelectionListener(); });
        }
        this.inputElement.element.addEventListener("change", function () { return _this.changeListener(); });
        if (this.yearOnly) {
            this.currentPage = calendar_utils_1.CALENDAR_VIEWS.YEARS;
            this.dateOnly = true;
        }
        if (this.monthOnly) {
            this.currentPage = calendar_utils_1.CALENDAR_VIEWS.MONTHS;
            this.dateOnly = true;
        }
    };
    UIDatePicker.prototype.detached = function () {
        var _this = this;
        var _a, _b, _c, _d, _e;
        if (((_a = this.disposables) === null || _a === void 0 ? void 0 : _a.length) > 0) {
            this.disposables.forEach(function (disposable) {
                disposable.dispose();
            });
        }
        (_c = (_b = this.inputElement) === null || _b === void 0 ? void 0 : _b.element) === null || _c === void 0 ? void 0 : _c.removeEventListener("clear", function () { return _this.clearSelectionListener(); });
        (_e = (_d = this.inputElement) === null || _d === void 0 ? void 0 : _d.element) === null || _e === void 0 ? void 0 : _e.removeEventListener("change", function () { return _this.changeListener(); });
    };
    UIDatePicker.prototype.dateChanged = function (newVal, oldVal) {
        if (newVal != oldVal) {
            if (this.date == null && this.errors != null && this.errors.length == 0) {
                this.dateLabel = null;
            }
            else {
                this.selectedDate = (0, calendar_utils_1.parseDate)(newVal, this.dateUtils);
                if (this.dateUtils.isValid(this.selectedDate)) {
                    this.errors = [];
                    this.month = this.dateUtils.getStartOfMonth(this.selectedDate);
                    this.dateLabel = ui_format_1.UIFormat.datetime(newVal, this.format);
                }
            }
        }
    };
    Object.defineProperty(UIDatePicker.prototype, "dateConfig", {
        get: function () {
            return {
                date: this.selectedDate,
                page: this.currentPage,
                minDate: (0, calendar_utils_1.parseDate)(this.minDate, this.dateUtils),
                maxDate: (0, calendar_utils_1.parseDate)(this.maxDate, this.dateUtils),
                disabled: this.disabledDatesList
            };
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(UIDatePicker.prototype, "title", {
        get: function () {
            return (0, calendar_utils_1.getTitle)(this.month, this.currentPage, this.translations, this.dateUtils);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(UIDatePicker.prototype, "headerOptions", {
        get: function () {
            return (0, calendar_utils_1.buildHeaderConfig)(this.month, this.currentPage, this.dateConfig, this.dateUtils, this.translations);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(UIDatePicker.prototype, "disabledDatesList", {
        get: function () {
            var _this = this;
            if (isArray(this.disabledDates)) {
                return this.disabledDates.map(function (d) {
                    var dt = (0, calendar_utils_1.parseDate)(d, _this.dateUtils);
                    return !isEmpty(dt) ? _this.dateUtils.getStartOfDay(dt).toISOString() : null;
                });
            }
            return this.disabledDates;
        },
        enumerable: false,
        configurable: true
    });
    UIDatePicker.prototype.headerClicked = function ($event) {
        var target = $event.target;
        if (target.dataset.tool) {
            if (target.dataset.tool === calendar_head_1.CalendarHead.TITLE) {
                if (this.currentPage !== calendar_utils_1.CALENDAR_VIEWS.YEARS) {
                    this.currentPage++;
                }
            }
            else {
                this.month = (0, calendar_utils_1.changeMonth)(this.month, this.currentPage, target.dataset.tool, this.dateUtils);
            }
        }
    };
    UIDatePicker.prototype.selectDate = function ($event) {
        if (!this.timeOnly) {
            var target = $event.target;
            if (target.dataset.date) {
                this.selectedPreset = null;
                this.updateDate(this.dateUtils.getStartOfDay(new Date(target.dataset.date)));
                if (this.closeOnSelect === true) {
                    this.dropDate.toggleDrop();
                }
            }
        }
    };
    UIDatePicker.prototype.selectMonth = function ($event) {
        var target = $event.target;
        if (target.dataset.date) {
            this.month = new Date(target.dataset.date);
            if (!this.yearOnly) {
                this.currentPage--;
            }
            else {
                this.updateDate(this.dateUtils.getStartOfDay(new Date(target.dataset.date)));
            }
            if (this.monthOnly && this.currentPage < calendar_utils_1.CALENDAR_VIEWS.MONTHS) {
                this.currentPage = calendar_utils_1.CALENDAR_VIEWS.MONTHS;
                this.updateDate(this.dateUtils.getStartOfDay(new Date(target.dataset.date)));
            }
        }
    };
    UIDatePicker.prototype.cancelSelection = function () {
        if (!this.yearOnly && !this.monthOnly) {
            this.currentPage = calendar_utils_1.CALENDAR_VIEWS.DAYS;
        }
    };
    UIDatePicker.prototype.clearSelection = function () {
        if (this.allowClear) {
            this.date = null;
            this.dateLabel = null;
        }
    };
    UIDatePicker.prototype.selectPreset = function (preset, cancelSelection) {
        if (cancelSelection === void 0) { cancelSelection = true; }
        if (cancelSelection)
            this.cancelSelection();
        this.selectedPreset = preset;
        if (this.closeOnSelect === true) {
            this.dropDate.toggleDrop();
        }
    };
    UIDatePicker.prototype.updateDate = function (dt, tm) {
        var _this = this;
        if (tm === void 0) { tm = this.date; }
        if (dt != null) {
            if (this.dateOnly) {
                dt.setHours(12, 0, 0, 0);
            }
            else if (tm != null) {
                dt.setHours(tm.getHours(), tm.getMinutes(), 0, 0);
            }
        }
        this.date = dt;
        this.dateLabel = ui_format_1.UIFormat.datetime(this.date, this.format);
        this.taskQueue.queueMicroTask(function () {
            _this.onChange({ date: _this.date });
        });
    };
    UIDatePicker.prototype.toggleUIDrop = function (isDate) {
        if (this.disabled || this.readonly)
            return;
        if (this.date == null) {
            if (this.autosetWhenOpened) {
                this.date = new Date();
            }
            else {
                this.initDateWhenOpened();
            }
        }
        if (!isDate) {
            ui_internal_1.UIInternal.broadcast("openTimePage");
        }
    };
    UIDatePicker.prototype.toggleDateDrop = function () {
        this.dropDate.toggleDrop();
    };
    UIDatePicker.prototype.toggleTimeDrop = function () {
        this.dropTime.toggleDrop();
    };
    UIDatePicker.prototype.changeLanguage = function () {
        this.translations = {
            "months": moment_1.default.months().map(function (x) { return x.charAt(0).toUpperCase() + x.substring(1); }),
            "monthsShort": moment_1.default.monthsShort().map(function (x) { return x.charAt(0).toUpperCase() + x.substring(1, 3); }),
            "weekdaysAbbrev": moment_1.default.weekdaysMin()
        };
    };
    __decorate([
        (0, aurelia_framework_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.twoWay }),
        __metadata("design:type", Date)
    ], UIDatePicker.prototype, "date", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", String)
    ], UIDatePicker.prototype, "minDate", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", String)
    ], UIDatePicker.prototype, "maxDate", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Object)
    ], UIDatePicker.prototype, "disabledDates", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", String)
    ], UIDatePicker.prototype, "format", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Boolean)
    ], UIDatePicker.prototype, "dateOnly", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Boolean)
    ], UIDatePicker.prototype, "displayWeek", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Boolean)
    ], UIDatePicker.prototype, "attachToViewport", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Boolean)
    ], UIDatePicker.prototype, "closeOnSelect", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Object)
    ], UIDatePicker.prototype, "yearOnly", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Object)
    ], UIDatePicker.prototype, "monthOnly", void 0);
    __decorate([
        aurelia_framework_1.bindable,
        __metadata("design:type", Function)
    ], UIDatePicker.prototype, "onChange", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.twoWay }),
        __metadata("design:type", Array)
    ], UIDatePicker.prototype, "presets", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.twoWay }),
        __metadata("design:type", Object)
    ], UIDatePicker.prototype, "selectedPreset", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Boolean)
    ], UIDatePicker.prototype, "autosetWhenOpened", void 0);
    __decorate([
        aurelia_framework_1.bindable,
        __metadata("design:type", Function)
    ], UIDatePicker.prototype, "initDateWhenOpened", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", String)
    ], UIDatePicker.prototype, "placeholder", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Boolean)
    ], UIDatePicker.prototype, "timeOnly", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Number)
    ], UIDatePicker.prototype, "startHour", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Number)
    ], UIDatePicker.prototype, "endHour", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Number)
    ], UIDatePicker.prototype, "hourInterval", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Number)
    ], UIDatePicker.prototype, "startMinute", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Number)
    ], UIDatePicker.prototype, "endMinute", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Number)
    ], UIDatePicker.prototype, "minuteInterval", void 0);
    __decorate([
        (0, aurelia_framework_1.computedFrom)("selectedDate", "currentPage", "minDate", "maxDate", "disabledDates"),
        __metadata("design:type", Object),
        __metadata("design:paramtypes", [])
    ], UIDatePicker.prototype, "dateConfig", null);
    __decorate([
        (0, aurelia_framework_1.computedFrom)("month", "currentPage", "translations"),
        __metadata("design:type", String),
        __metadata("design:paramtypes", [])
    ], UIDatePicker.prototype, "title", null);
    __decorate([
        (0, aurelia_framework_1.computedFrom)("month", "currentPage", "minDate", "maxDate", "translations"),
        __metadata("design:type", Object),
        __metadata("design:paramtypes", [])
    ], UIDatePicker.prototype, "headerOptions", null);
    UIDatePicker = __decorate([
        (0, aurelia_framework_1.customElement)("ui-date-picker"),
        (0, aurelia_framework_1.viewResources)(calendar_head_1.CalendarHead, days_page_1.DaysPage, months_page_1.MonthsPage, years_page_1.YearsPage, time_page_1.TimePage),
        __metadata("design:paramtypes", [Element, aurelia_i18n_1.I18N, aurelia_event_aggregator_1.EventAggregator, date_utils_1.DateUtils, aurelia_framework_1.BindingEngine, aurelia_framework_1.TaskQueue, config_1.Config])
    ], UIDatePicker);
    return UIDatePicker;
}(base_input_1.BaseInput));

//# sourceMappingURL=ui-date-picker.js.map
