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

export class products_loader {
    static async all() {
        const request = await fetch("/products/");
        const response = await request.json();
        
        return products_loader.#response_to_collection(response);
    }

    static #response_to_collection(response) {
        if (response.result !== "success") {
            return new Array();
        }

        if ("collection" in response) {
            return this.#list_response_to_collection(response);
        }

        return this.#single_response_to_collection(response);
    }

    static #single_response_to_collection(response) {
        const result = new Array();
        result.push(new product(response.product));
        
        return result;
    }

    static #list_response_to_collection(response) {
        const result = new Array();
        
        response.collection.forEach(serialized => {
            result.push(new product(serialized));
        });

        return result;
    }

    static async search_name(name) {
        return await products_loader.#search(
            "/product/search/name", 
            name
        ); 
    }

    static async search_author(author) {
        return await products_loader.#search(
            "/product/search/author", 
            author
        );
    }

    static async search_barcode(barcode) {
        return await products_loader.#search(
            "/product/get/barcode",
            barcode
        );
    }

    static async #search(path, parameter) {
        const coded = encodeURI(parameter);
        const request = await fetch(path + "/" + coded);
        const response = await request.json();
        
        return products_loader.#response_to_collection(response);
    }
}
