import { List } from '@iqser/common-ui/lib/utils';
import { AnnotationWrapper } from '@models/file/annotation.wrapper';
import { ALLOWED_KEYBOARD_SHORTCUTS } from './constants';

export function stopAndPrevent<T extends Event>($event: T) {
    $event.preventDefault();
    $event.stopPropagation();
}

export function stopAndPreventIfNotAllowed($event: KeyboardEvent) {
    if (!ALLOWED_KEYBOARD_SHORTCUTS.includes($event.key)) {
        stopAndPrevent($event);
    }
}

export function getId(item: string | AnnotationWrapper) {
    return typeof item === 'string' ? item : item.id;
}

export function getIds(items?: List | List<AnnotationWrapper>): List | undefined {
    return items?.map(getId);
}

export function isStringOrWrapper(value: unknown): value is string | AnnotationWrapper {
    return typeof value === 'string' || value instanceof AnnotationWrapper;
}

export function asList<T>(items: T[] | T): T[];
export function asList(items: string[] | string): string[];
export function asList(items: AnnotationWrapper[] | AnnotationWrapper): AnnotationWrapper[];
export function asList<T>(
    items: string[] | string | AnnotationWrapper[] | AnnotationWrapper | T | T[],
): string[] | AnnotationWrapper[] | T[] {
    if (!items) {
        return [];
    }

    if (typeof items === 'string') {
        return [items];
    }

    if (items instanceof AnnotationWrapper) {
        return [items];
    }

    const isArray = items instanceof Array;
    if (!isArray) {
        return [items];
    }

    return items;
}
