import { Component, OnInit, OnChanges, Input, Output, EventEmitter,
    ChangeDetectionStrategy, ElementRef, ViewChild, OnDestroy, Renderer2 } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { Subscription } from 'rxjs';
import { SessionService, LAYOUT_TYPE, CustomizationService } from '@pepperi/lib';

@Component({
    selector: 'pepperi-textarea',
    templateUrl: './textarea.component.html',
    styleUrls: ['./textarea.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class PepperiTextareaComponent implements OnChanges, OnInit, OnDestroy {
    @Input() key: string = '';
    @Input() value: string = '';
    @Input() label: string = '';
    @Input() required: boolean = false;
    @Input() disabled: boolean = false;
    @Input() readonly: boolean = false;
    @Input() maxFieldCharacters: number;
    @Input() textColor: string = '';
    @Input() xAlignment: string = '0';
    @Input() rowSpan: number = 1;
    @Input() lastFocusField: any;

    controlType = 'textarea';

    @Input() form: FormGroup = null;
    @Input() isActive: boolean = false;
    @Input() showTitle: boolean = true;
    @Input() layoutType: LAYOUT_TYPE = LAYOUT_TYPE.PepperiForm;

    @Output() valueChanged: EventEmitter<any> = new EventEmitter<any>();

    @ViewChild("input") input: ElementRef;

    LAYOUT_TYPE = LAYOUT_TYPE;
    fieldHeight = '';
    standAlone = false;
    isInEditMode: boolean = false;
    subscription: Subscription;

    constructor(
        // public dialogService: DialogService,
        public sessionService: SessionService,
        public customizationService: CustomizationService,
        private renderer: Renderer2,
        public _eref: ElementRef
    ) {
        const self = this;
        // this.subscription = this.dialogService.data.subscribe(data => {
        //     if (self.key === data.key) {
        //         self.changeValue(data.value);
        //     }
        // });
    }

    ngOnInit() {
        if (this.form === null) {
            this.standAlone = true;
            this.form = this.customizationService
                .getDefaultFromGroup(this.key, this.value, this.required, this.readonly, this.disabled, this.maxFieldCharacters);

            this.renderer.addClass(this._eref.nativeElement, CustomizationService.STAND_ALONE_FIELD_CLASS_NAME);
        }

        this.fieldHeight = this.customizationService.calculateFieldHeight(this.layoutType, this.rowSpan, this.standAlone);
    }

    ngOnChanges(changes: any) {
        const self = this;
        setTimeout(() => {
            if (self.lastFocusField) {
                self.lastFocusField.focus();
                self.lastFocusField = null;
            }
        }, 100);
    }

    ngOnDestroy() {
        if (this.valueChanged) {
            this.valueChanged.unsubscribe();
        }

        if (this.subscription) {
            this.subscription.unsubscribe();
        }
    }

    onBlur(event: any) {
        const value = event.target ? event.target.value : event;
        this.changeValue(value, event.relatedTarget);

        setTimeout(() => {
            if (this.isInEditMode) {
                this.isInEditMode = false;
            }
        }, 0);
    }

    changeValue(value: any, lastFocusedField: any = null) {
        if (value !== this.value) {
            this.value = value;
            this.customizationService.updateFormFieldValue(this.form, this.key, value);
            this.valueChanged.emit({ apiName: this.key, value: value, lastFocusedField: lastFocusedField });
        }
    }

    cardTemplateClicked(event: any) {
        this.openDialog();
    }

    openDialog() {
        // TODO:
        // const data = new DialogData(this.label, this.value,
        //     DialogDataType.TextArea,
        //     [],
        //     { 'key': this.key, 'value': this.value, 'disabled': this.disabled });
        // this.dialogService.openDialog(data, 'pepperi-modalbox', '24rem', '0', '90vw', '90vh');
    }
}
