import { EventEmitter, Component, ChangeDetectionStrategy, ChangeDetectorRef, Inject, Optional, Input, Output, ContentChild, ViewChild, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NgForm, Validators, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatDatepicker, MatDatepickerModule } from '@angular/material/datepicker';
import { NgxMatDatetimePickerModule, NgxMatTimepickerModule } from '@angular-material-components/datetime-picker';
import { __classPrivateFieldGet, __classPrivateFieldSet } from 'tslib';
import { v4 } from 'uuid';
import moment from 'moment';
import { DeviceDetectorService } from 'ngx-device-detector';
import { Subscription } from 'rxjs';
import { SdFormControl, FORM_CONFIG, SdViewDefDirective, SdLabelDefDirective, SdCommonModule } from '@sd-angular/core/common';
import { MAT_DATE_LOCALE, DateAdapter, MAT_DATE_FORMATS } from '@angular/material/core';
import { MomentDateAdapter, MAT_MOMENT_DATE_ADAPTER_OPTIONS, MatMomentDateModule } from '@angular/material-moment-adapter';
import { SdTranslateModule } from '@sd-angular/core/translate';
import { MatInputModule } from '@angular/material/input';
import { NgxMatMomentModule } from '@angular-material-components/moment-adapter';
import { MatIconModule } from '@angular/material/icon';

var _date, _name, _form, _subscription;
const MY_FORMATS = {
    parse: {
        dateInput: 'MM/YYYY',
    },
    display: {
        dateInput: 'MM/YYYY',
        monthYearLabel: 'MMM YYYY',
        dateA11yLabel: 'LL',
        monthYearA11yLabel: 'MMMM YYYY',
    },
};
class SdDateMonth {
    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.isRequired = false;
        this.sdChange = new EventEmitter();
        this.modelChange = new EventEmitter();
        _subscription.set(this, new Subscription());
        this.isFocused = false;
        this.onFocus = () => {
            this.isFocused = true;
        };
        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.onChange = (event) => {
            var _a, _b, _c, _d;
            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 (value) {
                if (new Date(__classPrivateFieldGet(this, _date)) !== value) {
                    this.modelChange.emit(value);
                    this.sdChange.emit(value);
                }
            }
            else {
                if (!((_d = this.formControl) === null || _d === void 0 ? void 0 : _d.value)) {
                    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.setMonthAndYear = (normalizedMonthAndYear, datepicker) => {
            const ctrlValue = this.formControl.value || moment();
            ctrlValue.month(normalizedMonthAndYear.month());
            ctrlValue.year(normalizedMonthAndYear.year());
            this.formControl.setValue(ctrlValue);
            datepicker.close();
            this.modelChange.emit(ctrlValue);
            this.sdChange.emit(ctrlValue);
        };
        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.isRequired = (val === '') || val;
        if (this.isRequired) {
            this.formControl.setValidators([Validators.required]);
        }
        else {
            this.formControl.clearValidators();
        }
    }
    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);
    }
    ngAfterViewInit() {
    }
}
_date = new WeakMap(), _name = new WeakMap(), _form = new WeakMap(), _subscription = new WeakMap();
SdDateMonth.decorators = [
    { type: Component, args: [{
                selector: 'sd-date-month',
                template: "<label *ngIf=\"!appearance && label && !sdLabelDef?.templateRef\" class=\"d-block mb-0 T14M\">{{label}} <span class=\"text-danger mb-2\"\r\n  *ngIf=\"required\">*</span></label>\r\n<ng-container *ngIf=\"sdLabelDef?.templateRef\" matSuffix>\r\n  <ng-container *ngTemplateOutlet=\"sdLabelDef.templateRef\">\r\n  </ng-container>\r\n</ng-container>\r\n<div class=\"d-flex align-items-center\" [class.sd-view]=\"sdView?.templateRef\" [class.c-focused]=\"isFocused\"\r\n     [class.c-disabled]=\"formControl.disabled\" (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 }\">\r\n    </ng-container>\r\n  </ng-container>\r\n  <ng-template #default>\r\n    <mat-form-field 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 [id]=\"id\" matInput (dateInput)=\"onChange($event)\" [autocomplete]=\"id\" autocorrect=\"off\"\r\n             [formControl]=\"formControl\" [required]=\"isRequired\" [matDatepicker]=\"pickerMonth\"\r\n             placeholder=\"{{ placeholder || label }}\" [min]=\"min\" [max]=\"max\" (focus)=\"onFocus()\" (blur)=\"onBlur()\"\r\n             #input/>\r\n\r\n      <mat-icon *ngIf=\"formControl?.value && !isRequired && !formControl.disabled\" class=\"pointer sd-suffix-icon\"\r\n                (click)=\"clear($event)\" matSuffix>cancel\r\n      </mat-icon>\r\n      <mat-icon class=\"pointer sd-suffix-icon\" (click)=\"!formControl?.disabled && pickerMonth.open()\" #btn matSuffix>\r\n        today\r\n      </mat-icon>\r\n\r\n      <mat-datepicker #pickerMonth [touchUi]=\"isMobileOrTablet\" startView=\"multi-year\"\r\n                      (monthSelected)=\"setMonthAndYear($event, pickerMonth)\"></mat-datepicker>\r\n\r\n      <mat-error *ngIf=\"formControl?.errors?.required && !disableErrorMessage\">\r\n        {{ \"This field is required\" | sdTranslate }}\r\n      </mat-error>\r\n      <mat-error *ngIf=\"formControl?.errors?.customValidator && !disableErrorMessage\">\r\n        <strong>{{ formControl?.errors?.customValidator }}</strong>\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_LOCALE, useValue: 'vi-VN' },
                    {
                        provide: DateAdapter,
                        useClass: MomentDateAdapter,
                        deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS],
                    },
                    { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS },
                ],
                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}"]
            },] }
];
SdDateMonth.ctorParameters = () => [
    { type: ChangeDetectorRef },
    { type: DeviceDetectorService },
    { type: undefined, decorators: [{ type: Inject, args: [FORM_CONFIG,] }, { type: Optional }] }
];
SdDateMonth.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 }],
    label: [{ type: Input }],
    placeholder: [{ type: Input }],
    defaultTime: [{ type: Input }],
    minDate: [{ type: Input }],
    maxDate: [{ type: Input }],
    validator: [{ type: Input }],
    sdChange: [{ 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 SdDateMonthModule {
}
SdDateMonthModule.decorators = [
    { type: NgModule, args: [{
                imports: [
                    CommonModule,
                    FormsModule,
                    ReactiveFormsModule,
                    MatInputModule,
                    MatIconModule,
                    MatFormFieldModule,
                    MatDatepickerModule,
                    MatMomentDateModule,
                    NgxMatDatetimePickerModule,
                    NgxMatTimepickerModule,
                    NgxMatMomentModule,
                    SdTranslateModule,
                    SdCommonModule
                ],
                declarations: [
                    SdDateMonth
                ],
                exports: [
                    SdCommonModule,
                    SdDateMonth
                ],
                providers: []
            },] }
];

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

export { SdDateMonth, SdDateMonthModule, MY_FORMATS as ɵa };
//# sourceMappingURL=sd-angular-core-date-month.js.map
