import { Directive, ElementRef, HostListener, inject, output, input } from '@angular/core'
import { UntilDestroy } from '@ngneat/until-destroy'

@UntilDestroy({ checkProperties: true })
@Directive({
	standalone: true,
	// eslint-disable-next-line @angular-eslint/directive-selector
	selector: '[longPress]',
})
export class LongPressDirective {
	private readonly _elementRef = inject<ElementRef<HTMLElement>>(ElementRef)

	readonly duration = input(700)

	readonly longPress = output()

	private touchTimeout: ReturnType<typeof setTimeout> | undefined

	constructor() {
		this._elementRef.nativeElement.addEventListener('contextmenu', (event) => {
			event.preventDefault()
		})
	}

	@HostListener('touchstart') touchstart(): void {
		this.touchTimeout = setTimeout(() => {
			this.longPress.emit()
		}, this.duration())
	}

	@HostListener('touchend') touchend(): void {
		this.touchEnd()
	}
	@HostListener('touchcancel') touchcancel(): void {
		this.touchEnd()
	}

	private touchEnd(): void {
		clearTimeout(this.touchTimeout)
	}
}
