import { KeyControl } from "./Keyboard";

export interface GameConstructor {
    new(canvas: HTMLCanvasElement, cx: CanvasRenderingContext2D, keys: KeyControl): any
};

class Selection {
    constructor(private elements: HTMLElement[]) {}

    /**
     * Run a callback for every selected item.
     */
    public forEach(callback: (e: HTMLElement) => {}) {
        this.elements.forEach(callback);
    }

    /**
     * Run a callback for selected canvases, with a 2d context & KeyControl established for use.
     */
    public forEachCanvas(callback: (canvas: HTMLCanvasElement, cx: CanvasRenderingContext2D, keys: KeyControl) => {}, tabIndex = -1) {
        this.elements.forEach(e => {
            if(e instanceof HTMLCanvasElement) {
                const cx = e.getContext("2d") as CanvasRenderingContext2D;
                const keys = new KeyControl(e, tabIndex);

                callback(e, cx, keys);
            }
        });
    }
}

/**
 * Wrap an HTML element or list of elements to bind them to behavior.
 *
 * @param selector A CSS selector or a literal Element
 */
export function Select(selector: string): Selection;
export function Select(selector: HTMLElement): Selection;
export function Select(selector: string | HTMLElement): Selection {
    if(typeof selector === "string") {
        const elementList = document.querySelectorAll(selector);
        const elements: HTMLElement[] = Array.prototype.slice.call(elementList);
        return new Selection(elements);
    } else {
        const elements = [selector];
        return new Selection(elements);
    }
}