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

var _from, _to, _name, _form, _c1, _c2, _subscription, _onChanges, _emit;
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 SdDateRange {
    constructor(cdRef, detectorService, formConfig) {
        this.cdRef = cdRef;
        this.detectorService = detectorService;
        this.formConfig = formConfig;
        this.id1 = `I${v4()}`;
        this.id2 = `I${v4()}`;
        _from.set(this, null);
        _to.set(this, null);
        this.isMobileOrTablet = false;
        _name.set(this, v4());
        _form.set(this, void 0);
        this.formControl = new FormControl();
        this.required = false;
        this.disableErrorMessage = false;
        this.sdChange = new EventEmitter();
        this.fromChange = new EventEmitter();
        this.toChange = new EventEmitter();
        this.control1 = new FormControl();
        _c1.set(this, v4());
        this.control2 = new FormControl();
        _c2.set(this, v4());
        _subscription.set(this, new Subscription());
        _onChanges.set(this, () => {
            const from = Date.isDate(__classPrivateFieldGet(this, _from)) ? moment(Date.toFormat(__classPrivateFieldGet(this, _from), 'MM/dd/yyyy HH:mm:ss'), 'MM/DD/YYYY HH:mm:ss') : null;
            const to = Date.isDate(__classPrivateFieldGet(this, _to)) ? moment(Date.toFormat(__classPrivateFieldGet(this, _to), 'MM/dd/yyyy HH:mm:ss'), 'MM/DD/YYYY HH:mm:ss') : null;
            this.control1.setValue(from, {
                emitEvent: false
            });
            this.control2.setValue(to, {
                emitEvent: false
            });
            this.formControl.setValue({
                from,
                to
            }, {
                emitEvent: false
            });
            this.cdRef.markForCheck();
        });
        this.onStartChange = (event) => {
            var _a, _b;
            const value = ((_a = event.value) === null || _a === void 0 ? void 0 : _a.toDate()) || null;
            const current = Date.toFormat((_b = event.value) === null || _b === void 0 ? void 0 : _b.toDate(), 'MM/dd/yyyy HH:mm:ss');
            const previous = Date.toFormat(__classPrivateFieldGet(this, _from), 'MM/dd/yyyy HH:mm:ss');
            if (previous !== current) {
                __classPrivateFieldSet(this, _from, value);
                this.fromChange.emit(value);
                __classPrivateFieldGet(this, _emit).call(this);
            }
        };
        this.onEndChange = (event) => {
            var _a, _b;
            const value = ((_a = event.value) === null || _a === void 0 ? void 0 : _a.toDate()) || null;
            const current = Date.toFormat((_b = event.value) === null || _b === void 0 ? void 0 : _b.toDate(), 'MM/dd/yyyy HH:mm:ss');
            const previous = Date.toFormat(__classPrivateFieldGet(this, _to), 'MM/dd/yyyy HH:mm:ss');
            if (previous !== current) {
                __classPrivateFieldSet(this, _to, value);
                this.toChange.emit(value);
                __classPrivateFieldGet(this, _emit).call(this);
            }
        };
        _emit.set(this, () => {
            var _a, _b;
            const from = ((_a = this.control1.value) === null || _a === void 0 ? void 0 : _a.toDate()) || null;
            const to = ((_b = this.control2.value) === null || _b === void 0 ? void 0 : _b.toDate()) || null;
            this.formControl.setValue({
                from,
                to
            }, {
                emitEvent: false
            });
            this.sdChange.emit(this.formControl.value);
            this.cdRef.markForCheck();
        });
        this.clear = () => {
            this.control1.setValue(null, {
                emitEvent: false
            });
            this.control2.setValue(null, {
                emitEvent: false
            });
            this.formControl.setValue({
                from: null,
                to: null
            }, {
                emitEvent: false
            });
            __classPrivateFieldSet(this, _from, this.control1.value);
            __classPrivateFieldSet(this, _to, this.control2.value);
            this.fromChange.emit(__classPrivateFieldGet(this, _from));
            this.toChange.emit(__classPrivateFieldGet(this, _to));
            this.sdChange.emit(this.formControl.value);
            this.cdRef.markForCheck();
        };
        this.isMobileOrTablet = !this.detectorService.isDesktop();
        this.cdRef.markForCheck();
    }
    set name(val) {
        if (val) {
            __classPrivateFieldSet(this, _name, val);
        }
    }
    set form(val) {
        if (val) {
            if (val instanceof NgForm) {
                __classPrivateFieldSet(this, _form, val.form);
            }
            else {
                __classPrivateFieldSet(this, _form, val);
            }
        }
    }
    // @Input() disabled = false;
    set disabled(val) {
        val = (val === '') || val;
        if (val) {
            this.formControl.disable();
        }
        else {
            this.formControl.enable();
        }
    }
    set _required(val) {
        this.required = (val === '') || val;
    }
    set _label(val) {
        this.label = val;
        this.qcId = hash({
            selector: 'sd-date-range',
            label: 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 from(val) {
        if (!Date.isDate(val)) {
            val = null;
        }
        if (__classPrivateFieldGet(this, _from) !== val) {
            __classPrivateFieldSet(this, _from, val);
            __classPrivateFieldGet(this, _onChanges).call(this);
        }
    }
    set to(val) {
        if (!Date.isDate(val)) {
            val = null;
        }
        if (__classPrivateFieldGet(this, _to) !== val) {
            __classPrivateFieldSet(this, _to, val);
            __classPrivateFieldGet(this, _onChanges).call(this);
        }
    }
    ngOnDestroy() {
        var _a, _b, _c;
        (_a = __classPrivateFieldGet(this, _form)) === null || _a === void 0 ? void 0 : _a.removeControl(__classPrivateFieldGet(this, _c1));
        (_b = __classPrivateFieldGet(this, _form)) === null || _b === void 0 ? void 0 : _b.removeControl(__classPrivateFieldGet(this, _c2));
        (_c = __classPrivateFieldGet(this, _form)) === null || _c === void 0 ? void 0 : _c.removeControl(__classPrivateFieldGet(this, _name));
        __classPrivateFieldGet(this, _subscription).unsubscribe();
    }
    ngOnInit() {
        var _a, _b, _c, _d;
        this.appearance = this.appearance || ((_a = this.formConfig) === null || _a === void 0 ? void 0 : _a.appearance);
        (_b = __classPrivateFieldGet(this, _form)) === null || _b === void 0 ? void 0 : _b.addControl(__classPrivateFieldGet(this, _c1), this.control1);
        (_c = __classPrivateFieldGet(this, _form)) === null || _c === void 0 ? void 0 : _c.addControl(__classPrivateFieldGet(this, _c2), this.control2);
        (_d = __classPrivateFieldGet(this, _form)) === null || _d === void 0 ? void 0 : _d.addControl(__classPrivateFieldGet(this, _name), this.formControl);
    }
    ngAfterViewInit() {
        // this.#subscription.add(merge(this.control1.valueChanges, this.control2.valueChanges).pipe(debounceTime(500)).subscribe(() => {
        //   const from = this.control1.value?.toDate() || null;
        //   const to = this.control2.value?.toDate() || null;
        //   const from1 = Date.toFormat(this.#from, 'dd/MM/yyyy HH:mm:ss');
        //   const from2 = Date.toFormat(from, 'dd/MM/yyyy HH:mm:ss');
        //   const to1 = Date.toFormat(this.#to, 'dd/MM/yyyy HH:mm:ss');
        //   const to2 = Date.toFormat(to, 'dd/MM/yyyy HH:mm:ss');
        //   if (from1 !== from2 || to1 !== to2) {
        //     if (from && to) {
        //       this.sdChange.emit({
        //         from,
        //         to
        //       });
        //     } else if (!from && !to) {
        //       this.sdChange.emit({
        //         from: null,
        //         to: null
        //       });
        //     }
        //   }
        // }));
        __classPrivateFieldGet(this, _onChanges).call(this);
    }
}
_from = new WeakMap(), _to = new WeakMap(), _name = new WeakMap(), _form = new WeakMap(), _c1 = new WeakMap(), _c2 = new WeakMap(), _subscription = new WeakMap(), _onChanges = new WeakMap(), _emit = new WeakMap();
SdDateRange.decorators = [
    { type: Component, args: [{
                selector: 'sd-date-range',
                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<mat-form-field class=\"sd-md\" [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  <mat-date-range-input [max]=\"max\" [min]=\"min\" [rangePicker]=\"picker\" [disabled]=\"formControl.disabled\">\r\n    <input aria-hidden=\"true\" [id]=\"id1\" autocomplete=\"off\" autocorrect=\"off\" matStartDate [formControl]=\"control1\"\r\n      (dateInput)=\"onStartChange($event)\" [placeholder]=\"formControl.disabled ? '' : ('Start' | sdTranslate)\"\r\n      [attr.data-qclabel]=\"label\" [attr.data-qcid]=\"qcId + 'input1'\">\r\n    <input aria-hidden=\"true\" [id]=\"id2\" [autocomplete]=\"id2\" autocorrect=\"off\" matEndDate [formControl]=\"control2\"\r\n      (dateInput)=\"onEndChange($event)\" [placeholder]=\"formControl.disabled ? '' : ('End' | sdTranslate)\"\r\n      [attr.data-qclabel]=\"label\" [attr.data-qcid]=\"qcId + 'input2'\">\r\n  </mat-date-range-input>\r\n  <mat-icon *ngIf=\"control1?.value || control2?.value\" class=\"pointer sd-suffix-icon\" (click)=\"clear()\" matSuffix>cancel\r\n  </mat-icon>\r\n  <mat-icon class=\"pointer sd-suffix-icon\" (click)=\"!formControl.disabled && picker.open()\" matSuffix>today\r\n  </mat-icon>\r\n  <mat-date-range-picker [touchUi]=\"isMobileOrTablet\" #picker></mat-date-range-picker>\r\n</mat-form-field>",
                providers: [{ provide: MAT_DATE_FORMATS, useValue: ɵ0 }],
                changeDetection: ChangeDetectionStrategy.OnPush,
                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-end-date:disabled,:host ::ng-deep .mat-form-field input.mat-start-date:disabled{color:#4d4d4d!important}:host ::ng-deep .mat-form-field .mat-placeholder-required{color:#f82c13}"]
            },] }
];
SdDateRange.ctorParameters = () => [
    { type: ChangeDetectorRef },
    { type: DeviceDetectorService },
    { type: undefined, decorators: [{ type: Inject, args: [FORM_CONFIG,] }, { type: Optional }] }
];
SdDateRange.propDecorators = {
    name: [{ type: Input }],
    appearance: [{ type: Input }],
    size: [{ type: Input }],
    form: [{ type: Input }],
    disabled: [{ type: Input }],
    _required: [{ type: Input, args: ['required',] }],
    _label: [{ type: Input, args: ['label',] }],
    _disableErrorMessage: [{ type: Input, args: ['disableErrorMessage',] }],
    _min: [{ type: Input, args: ['min',] }],
    _max: [{ type: Input, args: ['max',] }],
    from: [{ type: Input }],
    to: [{ type: Input }],
    sdChange: [{ type: Output }],
    fromChange: [{ type: Output }],
    toChange: [{ type: Output }],
    sdLabelDef: [{ type: ContentChild, args: [SdLabelDefDirective,] }]
};

class SdDateRangeModule {
}
SdDateRangeModule.decorators = [
    { type: NgModule, args: [{
                imports: [
                    CommonModule,
                    FormsModule,
                    ReactiveFormsModule,
                    MatFormFieldModule,
                    MatIconModule,
                    MatDatepickerModule,
                    MatMomentDateModule,
                    SdTranslateModule
                ],
                declarations: [
                    SdDateRange
                ],
                exports: [
                    SdDateRange
                ],
                providers: []
            },] }
];

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

export { SdDateRange, SdDateRangeModule, ɵ0 };
//# sourceMappingURL=sd-angular-core-date-range.js.map
