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

@Component({
    selector: 'cell-editor-numeric',
    template: `<input #input (keydown)="onKeyDown($event)" [(ngModel)]="value">`,
    styles: [
        `input {
            width: 100%;
            border: 1px solid grey;
        }`
    ],
})
export class NumericEditorComponent implements ICellEditorAngularComp, AfterViewInit {
    private params: ICellEditorParams;
    public value: number;
    private cancelBeforeStart = false;

    @ViewChild('input') input: ElementRef;

    agInit(params: ICellEditorParams): void {
        this.params = params;
        this.value = this.params.value;

        // Only cancel before start if the pressed key is numeric
        this.cancelBeforeStart = params.charPress && ('1234567890'.indexOf(params.charPress) < 0);
    }

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

    isCancelBeforeStart(): boolean {
        return this.cancelBeforeStart;
    }

    onKeyDown($event: KeyboardEvent) {
        if ( !this.isKeyPressedAllowed($event) ) {
            if ($event.preventDefault) {
                $event.preventDefault();
            }
        }
    }

    ngAfterViewInit(): void {
        setTimeout(() => {
            this.input.nativeElement.focus();
        });
    }

    private getCharCodeFromEvent(event): any {
        return (typeof event.which === 'undefined') ? event.keyCode : event.which;
    }

    private isCharNumeric(charStr): boolean {
        return !!/\d/.test(charStr);
    }

    private isKeyPressedAllowed(event): boolean {
        const charCode = this.getCharCodeFromEvent(event);
        const charStr = event.key ? event.key : String.fromCharCode(charCode);
        if (this.isCharNumeric(charStr)) {
            return true;
        } else if ( charStr === '.' && this.value % 1 === 0 ) {
            return true;
        } else if ( ['Backspace', 'Delete', 'ArrowLeft', 'ArrowRight', 'Enter'].includes(event.code) ) {
            return true;
        } else if ( charStr === 'a' && event.ctrlKey ) {
            return true;
        }

        return false;
    }
}
