import { autocomplete_request } from "./autocomplete_request";
import { product } from "./product";

export class autocomplete_database {
    #dataset;
    #completed;
    #current;
    #on_autocomplete;
    #on_create;
    #on_single_fail;
    #on_skip;
    #on_single_success;
    #finally;

    constructor(dataset) {
        this.#dataset = dataset;
        this.#completed = new Array();
        this.#current = null;
    }

    on_autocomplete(target) {
        this.#on_autocomplete = target;
        return this;
    }

    on_create(target) {
        this.#on_create = target;
        return this;
    }

    on_single_fail(target) {
        this.#on_single_fail = target;
        return this;
    }

    on_skip(target) {
        this.#on_skip = target;
        return this;
    }

    on_single_success(target) {
        this.#on_single_success = target;
        return this;
    }

    finally(target) {
        this.#finally = target;
        return this;
    }

    get current() {
        return this.#current;
    }

    async process() {
        for (const count of this.#dataset) {
            this.#current = count;

            if (query !== null) {
                query(count);
            }

            const request = new autocomplete_request(count.barcode);
            const response = await request.connect();

            if (!response.result) {
                throw new Error("Product barcode is not correct.");
            }

            const found = response.found;
            count.image = found.image;
            count.description = found.description;

            this.#completed.push(count);
        }

        return this;
    }
}