import { formscreen } from "./formscreen.js";
import { create_request } from "./create_request.js";
import { bool_response } from "./bool_response.js";
import { product_base } from "./product_base.js";
import { searcher } from "./searcher.js";
import { autocomplete_request } from "./autocomplete_request.js";
import { autocomplete_response } from "./autocomplete_response.js";
import { product_give_back } from "./product_give_back.js";

export class product_adder extends formscreen {
    #name;
    #description;
    #author;
    #barcode;
    #stock_count;
    #image;
    #loaded_image_type;
    #loaded_image;
    #image_preview;

    get _name() {
        return _("add-product");
    }

    async #autocomplete() {
        const barcode = this.#barcode();

        if (barcode.length === 0) {
            this._info = _("fill-barcode-first");
            return;
        }
        
        this._info = _("searching-in-the-web");

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

            if (!response.result) {
                throw new Error(response.cause);
            }
            
            const product = response.found;

            this.#name(product.title);
            this.#description(product.description);
            this.#author(product.author);
            this.#barcode(product.barcode);
            this.#loaded_image = product.image;
            this.#loaded_image_type = product.image_type;
            
            this.#update_image_preview();
            
            this._info = _("autocomplete-ready-check-results");
        } catch (error) {
            this._error = new String(error);
        }
    }

    #update_image_preview() {
        this.#image_preview.src = (
            "data:" 
            + this.#loaded_image_type 
            + ";base64,"
            + this.#loaded_image
        );
        this.#image_preview.style.opacity = "1";
    }

    get #autocomplete_button() {
        const button = document.createElement("div");
        button.classList.add("autocomplete-button");
        button.classList.add("button");

        const icon = document.createElement("span");
        icon.classList.add("material-icons")
        icon.innerText = "auto_fix_normal";
        button.appendChild(icon);

        const text = document.createElement("span");
        text.classList.add("text");
        text.innerText = _("autocomplete");
        button.appendChild(text);

        return button;
    }

    _build_form() {
        this.#loaded_image = null;
        this.#loaded_image_type = null;

        this.#name = this._create_input(
            "name", 
            _("name-prompt"), 
            _("name-sample")
        );

        this.#description = this._create_input(
            "description",
            _("description-prompt"),
            _("description-sample")
        );

        this.#author = this._create_input(
            "author",
            _("author-prompt"),
            _("author-sample")
        );

        this.#barcode = this._create_input(
            "barcode",
            _("barcode-prompt"),
            _("barcode-sample"),
            (input) => { input.type = "number"; }
        );

        this.#stock_count = this._create_input(
            "stock_count",
            _("stock-count-prompt"),
            _("stock-count-sample"),
            (input) => { input.type = "number"; }
        );

        this._create_input(
            "image",
            _("image-prompt"),
            "",
            (input) => {
                this.#image = input;
                input.type = "file";
                input.accept = "image/*";
                
                input.addEventListener("change", () => {
                    this.#load_image_from_file();
                });
            }
        );

        this.#image_preview = document.createElement("img");
        this.#image_preview.style.opacity = "0";
        this._append_child(this.#image_preview);

        const autocomplete = this.#autocomplete_button;
        this._append_child(autocomplete);

        autocomplete.addEventListener("click", () => {
            this.#autocomplete();
        });
    }

    #reset_image() {
        this.#loaded_image = null;
        this.#loaded_image_type = null;
        this.#image_preview.style.opacity = "0";
        this.#image_preview.src = "";
    }

    async #load_image_from_file() {
        if (this.#image.files.length === 0) {
            this.#reset_image();
        }

        const file = this.#image.files.item(0);
        const buffer = await file.arrayBuffer();
        let as_string = new String();

        new Uint8Array(buffer).forEach(letter => {
            as_string += String.fromCharCode(letter);
        });

        this.#loaded_image = btoa(as_string);
        this.#loaded_image_type = file.type;
        this.#update_image_preview();
    }

    get #ready_image() {
        if (this.#loaded_image === null) {
            throw new Error(_("load-any-image-first"));
        }

        return this.#loaded_image;
    }

    async #submit() {
        const product = new product_base();
        product.name = this.#name();
        product.description = this.#description();
        product.author = this.#author();
        product.stock_count = this.#stock_count();
        product.barcode = this.#barcode();

        const request = new create_request(product, this.#ready_image);
        const response = await request.connect();

        if (!response.result) {
            throw new Error(response.cause);
        }
    }

    async _process() {
        try {
            this._info = _("creating-new-product");
            await this.#submit();
            this._success = _("created-new-product-success");
        
            searcher.reload();

            setTimeout(() => {
                this.hide();
            }, 500);
        } catch (error) {
            this._error = new String(error);
        }
    }
}
