import {ICellEditorAngularComp} from 'ag-grid-angular';
import {AfterViewInit, Component, ElementRef, ViewChild} from '@angular/core';
import {ICellEditorParams} from 'ag-grid-community';
import {debounce} from '../../../../../utility';

@Component({
    selector: 'cell-editor-paragraph',
    template: `<input #input [value]="display" readonly (click)="onClick()">`,
    styles: [
        `input {
            width: 100%;
            border: 1px solid grey;
        }`
    ],
})
export class BooleanEditorComponent implements ICellEditorAngularComp, AfterViewInit {
    private params: ICellEditorParams;
    public value: boolean;

    public get display() {
        if ( typeof this.value === 'undefined' ) {
            return this.emptyValue;
        } else if ( this.value ) {
            return this.trueValue;
        } else {
            return this.falseValue;
        }
    }

    protected trueValue = 'True';
    protected falseValue = 'False';
    protected emptyValue = '';
    protected autoDismissDebounce = debounce(() => {
        this.params.stopEditing();
    }, 2000);

    @ViewChild('input') input: ElementRef;

    agInit(params: ICellEditorParams): void {
        this.params = params;
        this.value = this.params.value;
        console.log('bool params', {params});

        // @ts-ignore
        const values = params.colDef.additionalData.labelType.split('_');
        this.trueValue = values[0].charAt(0).toUpperCase() + values[0].slice(1);
        this.falseValue = values[1].charAt(0).toUpperCase() + values[1].slice(1);
    }

    getValue(): any {
        return this.value;
    }

    ngAfterViewInit(): void {
        this.onClick();
    }

    onClick() {
        if ( this.value === true ) {
            this.value = false;
        } else if ( this.value === false ) {
            this.value = undefined;
        } else {
            this.value = true;
        }

        this.autoDismissDebounce();
    }
}
