import { CommonModule } from '@angular/common';
import { EventEmitter, Component, ChangeDetectionStrategy, ChangeDetectorRef, Inject, Optional, Input, Output, ContentChild, ViewChild, NgModule } from '@angular/core';
import { NgForm, Validators, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatDatepicker, MatDatepickerModule } from '@angular/material/datepicker';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { SdButtonModule } from '@sd-angular/core/button';
import { SdFormControl, FORM_CONFIG, SdViewDefDirective, SdLabelDefDirective, SdCommonModule } from '@sd-angular/core/common';
import { SdTranslateModule } from '@sd-angular/core/translate';
import { __classPrivateFieldGet, __classPrivateFieldSet } from 'tslib';
import { MAT_DATE_FORMATS } from '@angular/material/core';
import moment from 'moment';
import { DeviceDetectorService } from 'ngx-device-detector';
import hash from 'object-hash';
import { Subscription } from 'rxjs';
import { v4 } from 'uuid';

var _date, _name, _form, _subscription;
const CUSTOM_DATE_FORMATS = {
    parse: {
        dateInput: 'DD/MM/YYYY',
    },
    display: {
        dateInput: 'DD/MM/YYYY',
        monthYearLabel: 'MMM YYYY',
        dateA11yLabel: 'LL',
        monthYearA11yLabel: 'MMMM YYYY',
    },
};
const ɵ0 = CUSTOM_DATE_FORMATS;
class SdDate {
    constructor(ref, deviceService, formConfig) {
        this.ref = ref;
        this.formConfig = formConfig;
        this.id = `I${v4()}`;
        this.isMobileOrTablet = false;
        _date.set(this, void 0);
        _name.set(this, v4());
        this.disableErrorMessage = false;
        this.formControl = new SdFormControl();
        _form.set(this, void 0);
        this.required = false;
        this.sdChange = new EventEmitter();
        this.sdFocus = new EventEmitter();
        this.modelChange = new EventEmitter();
        _subscription.set(this, new Subscription());
        this.isFocused = false;
        this.onFocus = () => {
            this.isFocused = true;
            this.sdFocus.emit();
        };
        this.onBlur = () => {
            this.isFocused = false;
        };
        this.onClick = () => {
            var _a;
            if ((_a = this.sdView) === null || _a === void 0 ? void 0 : _a.templateRef) {
                if (!this.formControl.disabled && !this.isFocused) {
                    this.focus();
                }
            }
        };
        this.blur = () => {
            var _a, _b;
            (_b = (_a = this.input) === null || _a === void 0 ? void 0 : _a.nativeElement) === null || _b === void 0 ? void 0 : _b.blur();
        };
        this.focus = () => {
            this.isFocused = true;
            setTimeout(() => {
                var _a, _b, _c;
                (_b = (_a = this.input) === null || _a === void 0 ? void 0 : _a.nativeElement) === null || _b === void 0 ? void 0 : _b.focus();
                (_c = this.datePicker) === null || _c === void 0 ? void 0 : _c.open();
                //
            }, 100);
        };
        this.onKeyDown = (event) => {
            const key = event.keyCode || event.charCode;
            let isShift = false;
            if (key === 16) {
                isShift = true;
            }
            // cho phép copy parse
            if (event.ctrlKey && (key === 67 || key === 86)) {
                console.log('action copy parse... datepicker');
                return true;
            }
            // Allow only Numeric Keys.
            if (((key >= 48 && key <= 57) ||
                key === 8 ||
                key <= 37 ||
                key <= 39 ||
                (key >= 96 && key <= 105) ||
                key === 191 ||
                key === 186 ||
                key === 59) &&
                isShift === false) {
                return true;
            }
            else {
                return false;
            }
        };
        this.onKeyup = event => {
            const currentVal = event.target.value;
            const formControl = this.formControl;
            let regex = /^([1-9]|([012][0-9])|(3[01]))\/([0]{0,1}[1-9]|1[012])\/\d\d\d\d$/g;
            if (currentVal && !regex.test(currentVal)) {
                setTimeout(() => {
                    this.isValid = true;
                    formControl.markAsDirty();
                    formControl.markAsTouched();
                    formControl.setErrors(Object.assign(Object.assign({}, formControl.errors), { date: `Chưa đúng định dạng 'dd/MM/yyyy'` }));
                }, 0);
            }
            else {
                setTimeout(() => {
                    this.isValid = false;
                    formControl.setErrors(Object.assign(Object.assign({}, formControl.errors), { date: null }));
                    this.formControl.updateValueAndValidity();
                }, 0);
            }
        };
        this.onChange = (event) => {
            var _a, _b, _c;
            const value = (_a = event.value) === null || _a === void 0 ? void 0 : _a.toDate();
            (_c = (_b = this.input) === null || _b === void 0 ? void 0 : _b.nativeElement) === null || _c === void 0 ? void 0 : _c.focus();
            if (!this.isValid) {
                if (new Date(__classPrivateFieldGet(this, _date)) !== value) {
                    this.modelChange.emit(value);
                    this.sdChange.emit(value);
                }
            }
            else {
                this.isValid = false;
                this.formControl.setValue(null);
                this.modelChange.emit(null);
                this.sdChange.emit(null);
            }
        };
        this.clear = ($event) => {
            $event === null || $event === void 0 ? void 0 : $event.stopPropagation();
            if (this.formControl.value) {
                this.formControl.setValue(null);
                this.modelChange.emit(null);
                this.sdChange.emit(null);
            }
        };
        this.isMobileOrTablet = !deviceService.isDesktop();
    }
    set name(val) {
        if (val) {
            __classPrivateFieldSet(this, _name, val);
        }
    }
    set _disableErrorMessage(val) {
        this.disableErrorMessage = val === '' || val;
        val = val === '' || val;
    }
    set _min(val) {
        if (Date.isDate(val)) {
            this.min = new Date(val);
        }
        else {
            this.min = null;
        }
    }
    set _max(val) {
        if (Date.isDate(val)) {
            this.max = new Date(val);
        }
        else {
            this.max = null;
        }
    }
    set form(val) {
        if (val) {
            if (val instanceof NgForm) {
                __classPrivateFieldSet(this, _form, val.form);
            }
            else {
                __classPrivateFieldSet(this, _form, val);
            }
        }
    }
    set disabled(val) {
        val = val === '' || val;
        if (val) {
            this.formControl.disable();
        }
        else {
            this.formControl.enable();
        }
    }
    set _required(val) {
        this.required = val === '' || val;
        if (this.required) {
            this.formControl.setValidators([Validators.required]);
        }
        else {
            this.formControl.clearValidators();
        }
    }
    set _inlineError(val) {
        this.inlineError = val;
        // this.#updateValidator();
        if (this.inlineError) {
            this.formControl.setValidators([this.customInlineErrorValidator()]);
            this.formControl.updateValueAndValidity();
        }
        else {
            this.formControl.clearValidators();
            this.formControl.updateValueAndValidity();
        }
    }
    set _label(val) {
        this.label = val;
        this.qcId = hash({
            selector: 'sd-date',
            label: val,
        });
    }
    set minDate(val) {
        if (Date.isDate(val)) {
            this.min = new Date(val);
        }
        else {
            this.min = null;
        }
    }
    set maxDate(val) {
        if (Date.isDate(val)) {
            this.max = new Date(val);
        }
        else {
            this.max = null;
        }
    }
    set model(val) {
        if (!Date.isDate(val)) {
            val = null;
        }
        if (__classPrivateFieldGet(this, _date) !== val) {
            __classPrivateFieldSet(this, _date, val);
            const date = Date.isDate(__classPrivateFieldGet(this, _date)) ? moment(Date.toFormat(__classPrivateFieldGet(this, _date), 'MM/dd/yyyy HH:mm:ss'), 'MM/DD/YYYY HH:mm:ss') : null;
            this.formControl.setValue(date);
        }
    }
    ngOnDestroy() {
        var _a;
        (_a = __classPrivateFieldGet(this, _form)) === null || _a === void 0 ? void 0 : _a.removeControl(__classPrivateFieldGet(this, _name));
        __classPrivateFieldGet(this, _subscription).unsubscribe();
    }
    ngOnInit() {
        var _a, _b;
        this.appearance = this.appearance || ((_a = this.formConfig) === null || _a === void 0 ? void 0 : _a.appearance);
        __classPrivateFieldGet(this, _subscription).add(this.formControl.sdChanges.subscribe(() => {
            // this.formControl.updateValueAndValidity();
            this.ref.markForCheck();
        }));
        (_b = __classPrivateFieldGet(this, _form)) === null || _b === void 0 ? void 0 : _b.addControl(__classPrivateFieldGet(this, _name), this.formControl);
    }
    // Hàm tạo Validators tùy chỉnh cho inlineError
    customInlineErrorValidator() {
        return (control) => {
            return { inlineError: true };
        };
    }
    ngAfterViewInit() { }
    focusInputElement() {
        var _a, _b;
        (_b = (_a = this.input) === null || _a === void 0 ? void 0 : _a.nativeElement) === null || _b === void 0 ? void 0 : _b.focus();
    }
}
_date = new WeakMap(), _name = new WeakMap(), _form = new WeakMap(), _subscription = new WeakMap();
SdDate.decorators = [
    { type: Component, args: [{
                selector: 'sd-date',
                template: "<ng-container *ngIf=\"!appearance && sdLabelDef?.templateRef\">\r\n  <ng-container *ngTemplateOutlet=\"sdLabelDef.templateRef\"> </ng-container>\r\n</ng-container>\r\n<label *ngIf=\"!appearance && label && !sdLabelDef?.templateRef\" class=\"d-block mb-0 T14M\"\r\n  >{{ label }} <span class=\"text-danger mb-2\" *ngIf=\"required\">*</span></label\r\n>\r\n<div\r\n  class=\"d-flex align-items-center\"\r\n  [class.sd-view]=\"sdView?.templateRef\"\r\n  [class.c-focused]=\"isFocused\"\r\n  [class.c-disabled]=\"formControl.disabled\"\r\n  (click)=\"onClick()\">\r\n  <ng-container *ngIf=\"sdView?.templateRef && !isFocused && !datePicker?.opened; else default\">\r\n    <ng-container *ngTemplateOutlet=\"sdView.templateRef; context: { value: formControl.value }\"> </ng-container>\r\n  </ng-container>\r\n  <ng-template #default>\r\n    <mat-form-field\r\n      class=\"sd-md\"\r\n      [ngClass]=\"{ 'sd-sm': size === 'sm', 'no-padding-wrapper': disableErrorMessage }\"\r\n      [appearance]=\"appearance || 'outline'\">\r\n      <mat-label *ngIf=\"appearance && label\">{{ label }}</mat-label>\r\n      <input\r\n        aria-hidden=\"true\"\r\n        [id]=\"id\"\r\n        matInput\r\n        (keyup)=\"onKeyup($event)\"\r\n        (keydown)=\"onKeyDown($event)\"\r\n        (dateChange)=\"onChange($event)\"\r\n        [autocomplete]=\"id\"\r\n        autocorrect=\"off\"\r\n        [formControl]=\"formControl\"\r\n        [required]=\"required\"\r\n        [matDatepicker]=\"picker2\"\r\n        [placeholder]=\"placeholder || (appearance ? label : '')\"\r\n        [min]=\"min\"\r\n        [max]=\"max\"\r\n        (focus)=\"onFocus()\"\r\n        (blur)=\"onBlur()\"\r\n        [attr.data-qclabel]=\"label\"\r\n        [attr.data-qcid]=\"qcId\"\r\n        #input\r\n        [maxLength]=\"10\" />\r\n      <ng-content select=\"[sdSuffixIcon]\" matSuffix></ng-content>\r\n      <mat-icon\r\n        *ngIf=\"formControl?.value && !required && !formControl.disabled\"\r\n        class=\"pointer sd-suffix-icon\"\r\n        (click)=\"clear($event)\"\r\n        matSuffix\r\n        >cancel\r\n      </mat-icon>\r\n\r\n      <mat-icon class=\"pointer sd-suffix-icon\" (click)=\"!formControl?.disabled && picker2.open()\" #btn matSuffix>today </mat-icon>\r\n\r\n      <mat-datepicker #picker2 [touchUi]=\"isMobileOrTablet\"></mat-datepicker>\r\n\r\n      <mat-error *ngIf=\"formControl?.errors?.required && formControl?.touched\">\r\n        <ng-container *ngIf=\"!disableErrorMessage\">{{ 'This field is required' | sdTranslate }}</ng-container>\r\n      </mat-error>\r\n      <mat-error *ngIf=\"formControl?.errors?.matDatepickerMin && formControl?.touched && !isFocused\">\r\n        <ng-container *ngIf=\"!disableErrorMessage\"\r\n          >{{ 'Min date' | sdTranslate }}:\r\n          <strong>{{ min | date : 'dd/MM/yyyy HH:mm' }}</strong>\r\n        </ng-container>\r\n      </mat-error>\r\n      <mat-error *ngIf=\"formControl?.errors?.matDatepickerMax && formControl?.touched && !isFocused\">\r\n        <ng-container *ngIf=\"!disableErrorMessage\"\r\n          >{{ 'Max date' | sdTranslate }}:\r\n          <strong>{{ max | date : 'dd/MM/yyyy HH:mm' }}</strong>\r\n        </ng-container>\r\n      </mat-error>\r\n      <mat-error *ngIf=\"formControl?.errors?.matDatetimePickerParse && formControl?.touched && !isFocused\">\r\n        <ng-container *ngIf=\"!disableErrorMessage\"\r\n          >{{ 'Parse error' | sdTranslate }}:\r\n          <strong>{{ formControl?.errors?.matDatetimePickerParse?.text }}</strong>\r\n        </ng-container>\r\n      </mat-error>\r\n      <mat-error *ngIf=\"formControl?.errors?.customValidator && formControl?.touched && !disableErrorMessage\">\r\n        <ng-container *ngIf=\"!disableErrorMessage\">{{ formControl?.errors?.customValidator }} </ng-container>\r\n      </mat-error>\r\n      <mat-error *ngIf=\"formControl?.errors?.date && formControl?.touched && !disableErrorMessage\">\r\n        <ng-container *ngIf=\"!disableErrorMessage\">{{ formControl?.errors?.date }} </ng-container>\r\n      </mat-error>\r\n      <mat-error *ngIf=\"formControl.errors?.inlineError && formControl?.touched && !disableErrorMessage\">\r\n        <ng-container *ngIf=\"!disableErrorMessage\">{{ inlineError }}</ng-container>\r\n      </mat-error>\r\n    </mat-form-field>\r\n  </ng-template>\r\n</div>\r\n",
                changeDetection: ChangeDetectionStrategy.OnPush,
                providers: [{ provide: MAT_DATE_FORMATS, useValue: ɵ0 }],
                styles: [":host{display:block;padding-top:5px}:host ::ng-deep .mat-form-field.no-padding-wrapper .mat-form-field-wrapper{padding-bottom:0}:host ::ng-deep .mat-form-field.mat-form-field-appearance-outline.mat-form-field-disabled .mat-form-field-outline{background:#f6f6f6;color:#e9e9e9}:host ::ng-deep .mat-form-field input.mat-input-element:disabled{color:#4d4d4d!important}:host ::ng-deep .mat-form-field .mat-placeholder-required{color:#f82c13}.sd-view:not(.c-focused):not(.c-disabled):hover{background-color:#ebecf0}"]
            },] }
];
SdDate.ctorParameters = () => [
    { type: ChangeDetectorRef },
    { type: DeviceDetectorService },
    { type: undefined, decorators: [{ type: Inject, args: [FORM_CONFIG,] }, { type: Optional }] }
];
SdDate.propDecorators = {
    name: [{ type: Input }],
    appearance: [{ type: Input }],
    _disableErrorMessage: [{ type: Input, args: ['disableErrorMessage',] }],
    _min: [{ type: Input, args: ['min',] }],
    _max: [{ type: Input, args: ['max',] }],
    size: [{ type: Input }],
    form: [{ type: Input }],
    disabled: [{ type: Input }],
    _required: [{ type: Input, args: ['required',] }],
    _inlineError: [{ type: Input, args: ['inlineError',] }],
    _label: [{ type: Input, args: ['label',] }],
    placeholder: [{ type: Input }],
    minDate: [{ type: Input }],
    maxDate: [{ type: Input }],
    validator: [{ type: Input }],
    sdChange: [{ type: Output }],
    sdFocus: [{ type: Output }],
    model: [{ type: Input }],
    modelChange: [{ type: Output }],
    sdView: [{ type: ContentChild, args: [SdViewDefDirective,] }],
    sdLabelDef: [{ type: ContentChild, args: [SdLabelDefDirective,] }],
    input: [{ type: ViewChild, args: ['input',] }],
    datePicker: [{ type: ViewChild, args: [MatDatepicker,] }]
};

class SdDateModule {
}
SdDateModule.decorators = [
    { type: NgModule, args: [{
                imports: [
                    CommonModule,
                    FormsModule,
                    ReactiveFormsModule,
                    MatInputModule,
                    MatIconModule,
                    MatFormFieldModule,
                    MatDatepickerModule,
                    SdTranslateModule,
                    SdCommonModule,
                    SdButtonModule
                ],
                declarations: [
                    SdDate
                ],
                exports: [
                    SdCommonModule,
                    SdDate
                ],
                providers: []
            },] }
];

/**
 * Generated bundle index. Do not edit.
 */

export { SdDate, SdDateModule };
//# sourceMappingURL=sd-angular-core-date.js.map
