import { __decorate, __extends } from "tslib";
import Component from 'vue-class-component';
import { Emit, Prop, Watch } from 'vue-property-decorator';
import { InputState } from '../../mixins/input-state/input-state';
import { InputWidth } from '../../mixins/input-width/input-width';
import { MediaQueries } from '../../mixins/media-queries/media-queries';
import ModulDate from '../../utils/modul-date/modul-date';
import uuid from '../../utils/uuid/uuid';
import { ModulVue } from '../../utils/vue/vue';
import { PERIODPICKER_NAME } from '../component-names';
import { MValidationMessage } from '../validation-message/validation-message';
import WithRender from './periodpicker.html?style=./periodpicker.scss';
var MDateRange = /** @class */ (function () {
    function MDateRange(from, to, hasValidFormat) {
        this.from = from;
        this.to = to;
        this.hasValidFormat = hasValidFormat;
    }
    Object.defineProperty(MDateRange.prototype, "fromIsoString", {
        get: function () {
            if (!this.from) {
                return undefined;
            }
            if (typeof this.from === 'string') {
                return this.from.includes('T') ? this.from : new ModulDate(this.from).toISOString();
            }
            else {
                return this.from.toISOString();
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MDateRange.prototype, "toIsoString", {
        get: function () {
            if (!this.to) {
                return undefined;
            }
            if (typeof this.to === 'string') {
                return this.to.includes('T') ? this.to : new ModulDate(this.to).endOfDay().toISOString();
            }
            else {
                return this.to.toISOString();
            }
        },
        enumerable: false,
        configurable: true
    });
    return MDateRange;
}());
export { MDateRange };
var MPeriodpicker = /** @class */ (function (_super) {
    __extends(MPeriodpicker, _super);
    function MPeriodpicker() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.validationMessageId = uuid.generate();
        _this.dateFromInternalValue = '';
        _this.dateToInternalValue = '';
        _this.fromIsFocused = false;
        _this.toIsFocused = false;
        _this.beginSelection = false;
        return _this;
    }
    MPeriodpicker_1 = MPeriodpicker;
    MPeriodpicker.prototype.emitNewValue = function (newValue) { };
    Object.defineProperty(MPeriodpicker.prototype, "firstInputState", {
        get: function () {
            var _this = this;
            return {
                props: {
                    focus: this.fromIsFocused,
                    value: this.dateFromInternalValue,
                    min: this.min,
                    max: this.max,
                    disabled: this.as().isDisabled,
                    waiting: this.as().isWaiting,
                    error: this.as().hasError,
                    valid: this.as().isValid,
                    readonly: this.as().readonly,
                    ariaDescribedby: this.validationMessageId
                },
                handlers: {
                    change: function (newValue) { return _this.onDateFromChange(newValue); },
                    blur: function () {
                        _this.fromIsFocused = false;
                        if (!_this.toIsFocused) {
                            _this.endSelection();
                        }
                    }
                }
            };
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MPeriodpicker.prototype, "secondInputState", {
        get: function () {
            var _this = this;
            return {
                props: {
                    focus: this.toIsFocused,
                    value: this.dateToInternalValue,
                    min: this.minDateTo,
                    max: this.max,
                    disabled: this.as().isDisabled,
                    waiting: this.as().isWaiting,
                    error: this.as().hasError,
                    valid: this.as().isValid,
                    readonly: this.as().readonly,
                    ariaDescribedby: this.validationMessageId
                },
                handlers: {
                    change: function (newValue) { return _this.onDateToChange(newValue); },
                    blur: function () {
                        _this.toIsFocused = false;
                        if (_this.beginSelection) {
                            _this.beginSelection = false;
                            _this.endSelection();
                        }
                    }
                }
            };
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MPeriodpicker.prototype, "internalValue", {
        get: function () {
            return new MDateRange(this.dateFromInternalValue, this.dateToInternalValue, MPeriodpicker_1.validateDateFormat(this.dateFromInternalValue)
                && MPeriodpicker_1.validateDateFormat(this.dateToInternalValue));
        },
        enumerable: false,
        configurable: true
    });
    MPeriodpicker.prototype.onValueChange = function (value) {
        this.dateFromInternalValue = MPeriodpicker_1.formatIsoDateToLocalString((this.value || { from: undefined }).from);
        this.dateToInternalValue = MPeriodpicker_1.formatIsoDateToLocalString((this.value || { to: undefined }).to);
    };
    Object.defineProperty(MPeriodpicker.prototype, "minDateTo", {
        get: function () {
            return this.internalValue.from ? this.internalValue.from : this.min;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MPeriodpicker.prototype, "hasTextfieldError", {
        get: function () {
            return this.as().hasError;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MPeriodpicker.prototype, "isTextfieldValid", {
        get: function () {
            return this.as().isValid;
        },
        enumerable: false,
        configurable: true
    });
    MPeriodpicker.prototype.onDateFromChange = function (newValue) {
        this.beginSelection = true;
        this.dateFromInternalValue = newValue;
        if (newValue) {
            var newDateValue = this.getNewModelValue(newValue);
            if (newValue && newDateValue) {
                this.toIsFocused = true;
            }
        }
    };
    MPeriodpicker.prototype.onDateToChange = function (newValue) {
        this.beginSelection = true;
        this.dateToInternalValue = newValue;
        if (newValue) {
            var newDateValue = this.getNewModelValue(newValue, true);
            if (newValue && newDateValue) {
                this.endSelection();
            }
        }
    };
    MPeriodpicker.prototype.getNewModelValue = function (newValue, endOfDay) {
        if (endOfDay === void 0) { endOfDay = false; }
        if (!newValue
            || (newValue.toString().length !== 10 && !(newValue instanceof Date) && !isFinite(newValue))
            || !MPeriodpicker_1.validateDateFormat(newValue.toString())) {
            return;
        }
        var modulDate = new ModulDate(newValue);
        var isoString = endOfDay ? modulDate.endOfDay().toISOString() : modulDate.beginOfDay().toISOString();
        return new Date(isoString);
    };
    MPeriodpicker.prototype.endSelection = function () {
        var newDateFrom = this.convertToIso ? this.internalDateFromIsoString : this.dateFromInternalValue;
        var newDateTo = this.convertToIso ? this.internalDateToIsoString : this.dateToInternalValue;
        var isDateFromValid = MPeriodpicker_1.validateDateFormat(this.dateFromInternalValue);
        var isDateToValid = MPeriodpicker_1.validateDateFormat(this.dateToInternalValue);
        this.emitNewValue(new MDateRange(isDateFromValid ? newDateFrom : this.dateFromInternalValue, isDateToValid ? newDateTo : this.dateToInternalValue, isDateFromValid && isDateToValid));
        this.beginSelection = false;
    };
    Object.defineProperty(MPeriodpicker.prototype, "internalDateFromIsoString", {
        get: function () {
            return this.getNewModelValue(this.dateFromInternalValue);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MPeriodpicker.prototype, "internalDateToIsoString", {
        get: function () {
            return this.getNewModelValue(this.dateToInternalValue, true);
        },
        enumerable: false,
        configurable: true
    });
    MPeriodpicker.validateDateFormat = function (dateString) {
        try {
            return new ModulDate(dateString) ? true : false;
        }
        catch (_a) {
            return false;
        }
    };
    /**
     * This method convert a date or a iso string into a local date string with format YYYY-MM-DD
     *
     * @param date
     */
    MPeriodpicker.formatIsoDateToLocalString = function (date) {
        if (!date) {
            return '';
        }
        if (!this.validateDateFormat(date)) {
            return date;
        }
        var _date = undefined;
        if (typeof date === 'string') {
            _date = new Date(date.includes('T') ? date : new Date(date + "T00:00"));
        }
        else if (date instanceof Date) {
            _date = date;
        }
        if (!_date) {
            return;
        }
        var month = '' + (_date.getMonth() + 1);
        var day = '' + _date.getDate();
        var year = _date.getFullYear();
        if (month.length < 2) {
            month = '0' + month;
        }
        if (day.length < 2) {
            day = '0' + day;
        }
        return [year, month, day].join('-');
    };
    var MPeriodpicker_1;
    __decorate([
        Prop()
    ], MPeriodpicker.prototype, "value", void 0);
    __decorate([
        Prop()
    ], MPeriodpicker.prototype, "min", void 0);
    __decorate([
        Prop()
    ], MPeriodpicker.prototype, "max", void 0);
    __decorate([
        Prop({
            default: true
        })
    ], MPeriodpicker.prototype, "convertToIso", void 0);
    __decorate([
        Emit('input')
    ], MPeriodpicker.prototype, "emitNewValue", null);
    __decorate([
        Watch('value', { immediate: true })
    ], MPeriodpicker.prototype, "onValueChange", null);
    MPeriodpicker = MPeriodpicker_1 = __decorate([
        WithRender,
        Component({
            components: {
                MValidationMessage: MValidationMessage
            },
            mixins: [
                MediaQueries,
                InputState,
                InputWidth
            ]
        })
    ], MPeriodpicker);
    return MPeriodpicker;
}(ModulVue));
export { MPeriodpicker };
var PeriodpickerPlugin = {
    install: function (v) {
        v.component(PERIODPICKER_NAME, MPeriodpicker);
    }
};
export default PeriodpickerPlugin;
//# sourceMappingURL=periodpicker.js.map