import { Directive, ElementRef, HostListener } from '@angular/core';

/*
    created by Ajith A Pradeep
    created on 03/03/2023
*/
@Directive({
    selector: '[numberOnly]'
})
export class NumberOnlyDirective {

    private regex: RegExp = new RegExp(/^\d*\.?\d{0,2}$/g);

    constructor(private el: ElementRef) { }

    // Listen for all keydown events on the input field
    @HostListener('keydown', ['$event'])
    onKeyDown(event: KeyboardEvent) {
        // Allow backspace, delete, and navigation keys (arrows)
        if ([46, 8, 9, 27, 13, 110, 190].indexOf(event.keyCode) !== -1 ||
            // Allow Ctrl/Cmd+A, Ctrl/Cmd+C, Ctrl/Cmd+X
            (event.keyCode === 65 || event.keyCode === 67 || event.keyCode === 88) && (event.ctrlKey || event.metaKey)) {
            return;
        }
        // Do not allow anything else that is not a number or decimal point
        if ((event.shiftKey || event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105) && event.keyCode !== 190 && event.keyCode !== 110) {
            event.preventDefault();
        }
    }

    // Listen for all input events on the input field (copy-paste, drag-and-drop, etc.)
    @HostListener('input', ['$event']) onInputChange(event: any) {
        const initialValue = this.el.nativeElement.value;
        const newValue = initialValue.replace(/[^0-9\.]/g, ''); // Remove any character that isn't a number or decimal point
        const parts = newValue.split('.');
        if (parts.length > 1) {
            // Limit to two decimal places
            this.el.nativeElement.value = `${parts[0]}.${parts[1].substring(0, 2)}`;
        } else {
            this.el.nativeElement.value = parts[0];
        }
        if (initialValue !== this.el.nativeElement.value) {
            // Emit change event to update host component property
            event.stopPropagation();
            this.el.nativeElement.dispatchEvent(new Event('input'));
        }
    }
}