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 __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
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);
};
import { EventAggregator } from 'aurelia-event-aggregator';
import { Internationalization } from './../../constants/constants';
import { bindable, BindingEngine, bindingMode, computedFrom, customElement, viewResources } from "aurelia-framework";
import { endOfDay, endOfMonth, endOfWeek, isBefore, isValid, startOfDay, startOfMonth, startOfWeek } from "date-fns";
import { UIFormat } from "../../utils/ui-format";
import { CalendarHead } from "./calendar-head";
import { buildHeaderConfig, CALENDAR_VIEWS, changeMonth, getTitle, parseDate } from "./calendar-utils";
import { DaysPage } from "./days-page";
import { MonthsPage } from "./months-page";
import { TimePage } from "./time-page";
import { YearsPage } from "./years-page";
import { I18N } from 'aurelia-i18n';
import moment from 'moment';
import { DateUtils } from '../../utils/date-utils';
import { UIInternal } from '../../utils/ui-internal';
import { Config } from '../../config';
import { BaseInput } from './../forms/base-input';
export var UIRangePickerSelectionMode;
(function (UIRangePickerSelectionMode) {
    UIRangePickerSelectionMode["Day"] = "day";
    UIRangePickerSelectionMode["Week"] = "week";
    UIRangePickerSelectionMode["Month"] = "month";
    UIRangePickerSelectionMode["MonthToMonth"] = "monthToMonth";
})(UIRangePickerSelectionMode || (UIRangePickerSelectionMode = {}));
export var UIRangePicker = (function (_super) {
    __extends(UIRangePicker, _super);
    function UIRangePicker(element, i18n, eventAggregator, dateUtils, bindingEngine, config) {
        var _this = _super.call(this, element) || this;
        _this.i18n = i18n;
        _this.eventAggregator = eventAggregator;
        _this.dateUtils = dateUtils;
        _this.bindingEngine = bindingEngine;
        _this.config = config;
        _this.selection = UIRangePickerSelectionMode.Day;
        _this.format = "DD/MM/yyyy";
        _this.useOnAgGrid = true;
        _this.attachToViewport = true;
        _this.presets = [];
        _this.selectedPreset = null;
        _this.autosetWhenOpened = true;
        _this.placeholder = "";
        _this.translations = Internationalization.datePickerTranslationsEN;
        _this.month = startOfMonth(new Date());
        _this.currentPage = CALENDAR_VIEWS.DAYS;
        _this.VIEWS = CALENDAR_VIEWS;
        _this.selectedDate = [null, null];
        _this.weekStartsOn = 1;
        _this.changeListener = function () {
            if (_this.dateLabel == null || _this.dateLabel == '') {
                _this.dateFrom = null;
                _this.dateTo = null;
            }
            else {
                _this.errors = [];
                var dateLabels = _this.dateLabel.split(' - ', 2);
                if (dateLabels != null && dateLabels.length == 2) {
                    var mFrom = moment(dateLabels[0], _this.format, true);
                    if (mFrom.isValid()) {
                        _this.dateFrom = _this.updateDate(mFrom.toDate());
                    }
                    else {
                        _this.errors.push(_this.i18n.tr("validation.invalidDate", { ns: "common" }));
                        _this.dateFrom = null;
                    }
                    var mTo = moment(dateLabels[1], _this.format, true);
                    if (mTo.isValid()) {
                        _this.dateTo = _this.updateDate(mTo.toDate());
                    }
                    else {
                        _this.errors.push(_this.i18n.tr("validation.invalidDate", { ns: "common" }));
                        _this.dateTo = null;
                    }
                }
            }
        };
        element.focus = function () { return _this.inputElement.focus(); };
        _this.disposables = new Array();
        _this.displayWeek = _this.config.globalConfig.displayWeekPicker;
        return _this;
    }
    UIRangePicker.prototype.bind = function () {
        var _this = this;
        _super.prototype.bind.call(this);
        if (this.dateFrom != undefined && this.dateTo != undefined && this.dateUtils.isAfter(moment(this.dateFrom), moment(this.dateTo)))
            throw Error("DateFrom cannot be after dateTo");
        if (this.selection == UIRangePickerSelectionMode.Week && !this.displayWeek) {
            this.displayWeek = true;
        }
        else if (this.selection == UIRangePickerSelectionMode.MonthToMonth) {
            this.currentPage = CALENDAR_VIEWS.MONTHS;
        }
        this.changeLanguageSubscription = this.eventAggregator.subscribe(UIInternal.EVT_CHANGE_LANGUAGE, function () {
            _this.changeLanguage();
        });
        this.changeLanguage();
        if (this.selectedPreset != null) {
            this.selectDateFromPreset();
        }
        this.dateChanged();
        this.disposables.push(this.bindingEngine.propertyObserver(this, "selectedPreset").subscribe(function () {
            if (_this.selectedPreset != null) {
                _this.selectDateFromPreset();
                if (_this.selectedPreset.action != null) {
                    _this.selectedPreset.action();
                }
            }
        }));
    };
    UIRangePicker.prototype.selectDateFromPreset = function () {
        this.dateFrom = this.dateUtils.isValid(this.selectedPreset.preset[0]) ? this.updateDate(this.selectedPreset.preset[0]) : undefined;
        this.dateTo = this.dateUtils.isValid(this.selectedPreset.preset[1]) ? this.updateDate(this.selectedPreset.preset[1]) : undefined;
    };
    UIRangePicker.prototype.unbind = function () {
        this.changeLanguageSubscription.dispose();
    };
    UIRangePicker.prototype.attached = function () {
        var _this = this;
        if (this.allowClear) {
            this.inputElement.allowClear = true;
            this.inputElement.element.addEventListener("clear", function () { return _this.clearSelection(); });
        }
        this.inputElement.element.addEventListener("change", function () { return _this.changeListener(); });
    };
    UIRangePicker.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.clearSelection(); });
        (_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(); });
    };
    UIRangePicker.prototype.dateChanged = function () {
        this.dateFromChanged(false);
        this.dateToChanged(false);
        this.computeLabel();
    };
    UIRangePicker.prototype.dateFromChanged = function (computeLabel) {
        if (computeLabel === void 0) { computeLabel = true; }
        if (this.dateFrom == null && this.errors != null && this.errors.length == 0) {
            this.selectedDate[0] = null;
            this.selectedDate[1] = null;
            this.month = moment().startOf("month").toDate();
            this.dateLabel = null;
        }
        else {
            this.selectedDate[0] = parseDate(this.dateFrom, this.dateUtils);
            if (isValid(this.selectedDate[0])) {
                this.errors = [];
                this.month = startOfMonth(this.selectedDate[0]);
            }
        }
        if (computeLabel) {
            this.computeLabel();
        }
    };
    UIRangePicker.prototype.dateToChanged = function (computeLabel) {
        if (computeLabel === void 0) { computeLabel = true; }
        if (this.dateTo == null && this.errors != null && this.errors.length == 0) {
            this.selectedDate[1] = null;
            this.dateLabel = null;
        }
        else {
            this.selectedDate[1] = parseDate(this.dateTo, this.dateUtils);
            if (isValid(this.selectedDate[1])) {
                this.errors = [];
                this.month = startOfMonth(this.month);
            }
        }
        if (computeLabel) {
            this.computeLabel();
        }
    };
    UIRangePicker.prototype.computeLabel = function () {
        var fromDate = this.selectedDate[0];
        var toDate = this.selectedDate[1];
        if (fromDate == null && toDate == null) {
            this.dateLabel = null;
        }
        else {
            this.dateLabel = "".concat(this.dateUtils.isSameOrBefore(fromDate, Date.MIN_DATE) ? "..." : UIFormat.date(fromDate, this.format), " - ").concat(this.dateUtils.isSameOrAfter(toDate, Date.MAX_DATE) ? "..." : UIFormat.date(toDate, this.format));
        }
    };
    Object.defineProperty(UIRangePicker.prototype, "rangeConfig", {
        get: function () {
            return {
                date: this.selecting ? [this.selecting, this.hilight] : this.selectedDate,
                page: this.currentPage,
                minDate: parseDate(this.minDate, this.dateUtils),
                maxDate: parseDate(this.maxDate, this.dateUtils),
                disabled: []
            };
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(UIRangePicker.prototype, "title", {
        get: function () {
            return getTitle(this.month, this.currentPage, this.translations, this.dateUtils);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(UIRangePicker.prototype, "headerOptions", {
        get: function () {
            return buildHeaderConfig(this.month, this.currentPage, __assign(__assign({}, this.rangeConfig), { page: this.currentPage }), this.dateUtils, this.translations);
        },
        enumerable: false,
        configurable: true
    });
    UIRangePicker.prototype.headerClicked = function ($event) {
        var target = $event.target;
        if (target.dataset.tool) {
            if (target.dataset.tool === CalendarHead.TITLE) {
                if (this.currentPage !== CALENDAR_VIEWS.YEARS) {
                    this.currentPage++;
                }
            }
            else {
                this.month = changeMonth(this.month, this.currentPage, target.dataset.tool, this.dateUtils);
            }
        }
    };
    UIRangePicker.prototype.selectDate = function ($event) {
        var target = $event.target;
        if (target.dataset.date) {
            var date = new Date(target.dataset.date);
            if (this.selection == UIRangePickerSelectionMode.Week || (target.dataset.week && this.selection == UIRangePickerSelectionMode.Day)) {
                this.selectedPreset = null;
                this.dateFrom = date ? this.updateDate(startOfWeek(date, { weekStartsOn: this.weekStartsOn })) : null;
                this.dateTo = date ? this.updateDate(endOfWeek(date, { weekStartsOn: this.weekStartsOn })) : null;
            }
            else if (this.selection == UIRangePickerSelectionMode.Month) {
                this.selectedPreset = null;
                this.dateFrom = date ? this.updateDate(startOfMonth(date)) : null;
                this.dateTo = date ? this.updateDate(endOfMonth(date)) : null;
            }
            else {
                this.internalSelectDate(date, startOfDay, endOfDay);
            }
        }
    };
    UIRangePicker.prototype.selectMonth = function ($event) {
        var target = $event.target;
        if (target.dataset.date) {
            var date = new Date(target.dataset.date);
            if (this.selection == UIRangePickerSelectionMode.MonthToMonth && this.currentPage == CALENDAR_VIEWS.MONTHS) {
                this.internalSelectDate(date, startOfMonth, endOfMonth);
            }
            else {
                this.month = date;
                this.currentPage--;
            }
        }
    };
    UIRangePicker.prototype.internalSelectDate = function (date, dateFromFn, dateToFn) {
        this.selectedPreset = null;
        if (this.selecting) {
            if (isBefore(date, this.selecting)) {
                this.dateFrom = this.updateDate(dateFromFn(date));
                this.dateTo = this.updateDate(dateToFn(this.selecting));
            }
            else {
                this.dateFrom = this.updateDate(dateFromFn(this.selecting));
                this.dateTo = this.updateDate(dateToFn(date));
            }
            this.selecting = null;
        }
        else {
            this.selecting = date;
        }
    };
    UIRangePicker.prototype.cancelSelection = function () {
        this.selecting = null;
        this.currentPage = CALENDAR_VIEWS.DAYS;
    };
    UIRangePicker.prototype.clearSelection = function () {
        this.selecting = null;
        this.selectedDate = [null, null];
        this.dateFrom = null;
        this.dateTo = null;
        this.dateLabel = null;
    };
    UIRangePicker.prototype.highlightDate = function ($event) {
        var target = $event.target;
        if (target.dataset.date) {
            this.hilight = new Date(target.dataset.date);
        }
    };
    UIRangePicker.prototype.highlightMonth = function ($event) {
        if (this.selection == UIRangePickerSelectionMode.MonthToMonth) {
            this.highlightDate($event);
        }
    };
    UIRangePicker.prototype.selectPreset = function (preset, cancelSelection) {
        if (cancelSelection === void 0) { cancelSelection = true; }
        if (cancelSelection)
            this.cancelSelection();
        this.selectedPreset = preset;
    };
    UIRangePicker.prototype.toggleUIDrop = function () {
        if (!this.autosetWhenOpened) {
            return;
        }
        if (this.dateFrom == null) {
            this.dateFrom = this.updateDate(new Date());
        }
        if (this.dateTo == null) {
            this.dateTo = this.updateDate(new Date());
        }
    };
    UIRangePicker.prototype.changeLanguage = function () {
        this.translations = {
            "months": moment.months().map(function (x) { return x.charAt(0).toUpperCase() + x.substring(1); }),
            "monthsShort": moment.monthsShort().map(function (x) { return x.charAt(0).toUpperCase() + x.substring(1, 3); }),
            "weekdaysAbbrev": moment.weekdaysMin()
        };
    };
    UIRangePicker.prototype.updateDate = function (dt) {
        var date = dt != null ? new Date(dt) : new Date();
        return this.dateUtils.setHours(date, 12);
    };
    __decorate([
        bindable({ defaultBindingMode: bindingMode.twoWay }),
        __metadata("design:type", Date)
    ], UIRangePicker.prototype, "dateFrom", void 0);
    __decorate([
        bindable({ defaultBindingMode: bindingMode.twoWay }),
        __metadata("design:type", Date)
    ], UIRangePicker.prototype, "dateTo", void 0);
    __decorate([
        bindable({ defaultBindingMode: bindingMode.oneTime }),
        __metadata("design:type", String)
    ], UIRangePicker.prototype, "selection", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", String)
    ], UIRangePicker.prototype, "minDate", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", String)
    ], UIRangePicker.prototype, "maxDate", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", String)
    ], UIRangePicker.prototype, "format", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", Boolean)
    ], UIRangePicker.prototype, "displayWeek", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", Boolean)
    ], UIRangePicker.prototype, "useOnAgGrid", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", Boolean)
    ], UIRangePicker.prototype, "attachToViewport", void 0);
    __decorate([
        bindable({ defaultBindingMode: bindingMode.twoWay }),
        __metadata("design:type", Array)
    ], UIRangePicker.prototype, "presets", void 0);
    __decorate([
        bindable({ defaultBindingMode: bindingMode.twoWay }),
        __metadata("design:type", Object)
    ], UIRangePicker.prototype, "selectedPreset", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", Boolean)
    ], UIRangePicker.prototype, "autosetWhenOpened", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", String)
    ], UIRangePicker.prototype, "placeholder", void 0);
    __decorate([
        computedFrom("selectedDate", "hilight", "selecting", "minDate", "maxDate", "disabledDates"),
        __metadata("design:type", Object),
        __metadata("design:paramtypes", [])
    ], UIRangePicker.prototype, "rangeConfig", null);
    __decorate([
        computedFrom("month", "currentPage", "translations"),
        __metadata("design:type", String),
        __metadata("design:paramtypes", [])
    ], UIRangePicker.prototype, "title", null);
    __decorate([
        computedFrom("month", "currentPage", "minDate", "maxDate"),
        __metadata("design:type", Object),
        __metadata("design:paramtypes", [])
    ], UIRangePicker.prototype, "headerOptions", null);
    UIRangePicker = __decorate([
        customElement("ui-range-picker"),
        viewResources(CalendarHead, DaysPage, MonthsPage, YearsPage, TimePage),
        __metadata("design:paramtypes", [Element, I18N, EventAggregator, DateUtils, BindingEngine, Config])
    ], UIRangePicker);
    return UIRangePicker;
}(BaseInput));

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