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

/**
 * This class is responsible for loading assets from the server.
 */
export class assets_getter {
    #app_url;
    
    /**
     * This create new assets getter.
     *  
     * @param {string} app_url - This is base app url
     */
    constructor(app_url) {
        this.#app_url = app_url;
    }

    /**
     * This fetch file from the config directory.
     * 
     * @async
     * @param {string} file - Name of the file to load
     * @returns {string, object} - Content of the file, or object if json
     * @throws {Error} - When file not exists on the server
     * @throws {TypeError} - When JSON file is bad formated
     */
    async load(file) {
        const url = this.#get_url(file);
        const result = await fetch(url);

        if (!result.ok) {
            let info = `Can not load file: "${url}", `;
            info += `status: "${result.status}".`;

            throw new Error(info);
        }

        if (this.#is_json(file)) {
            try {
                return await result.json();
            } catch (error) {
                let info = `JSON file "${file}" is bad formated. `;
                info += `More: "${error.message}".`;

                throw new TypeError(info);
            }   
        }

        return await result.text();
    }

    /**
     * This return url for texture, from texture name or room.
     * 
     * @param {string, room} target - Name or room of the texture
     * @returns {string} Link to the texture
     */
    texture(target) {
        if (target instanceof room) {
            target = target.texture;
        }

        return this.#get_url(`textures/${target}`);
    }

    /**
     * @async
     * @returns {object} - Return enviroment json as object
     */
    get enviroment() {
        return this.load("enviroment.json");
    }

    /**
     * @async
     * @returns {object} - Return items json as object
     */
    get items() {
        return this.load("items.json");
    }

    /**
     * @async
     * @returns {object} - Return rooms json as object
     */
    get rooms() {
        return this.load("rooms.json");
    }


    /**
     * @returns {string} - Base config directory on server
     */
    get #base_url() {
        return "/static/config";
    }

    /**
     * This function generate full URL to the file on server.
     * 
     * @param {string} file - Name of the file in config location
     * @returns {string} - Full path to the file on server 
     */
    #get_url(file) {
        return `${this.#app_url}/${this.#base_url}/${file}`;        
    }

    /**
     * This function check that file is json.
     * 
     * @param {string} file - Name of the file to load
     * @returns {bool} - True if file is json, os false when not
     */
    #is_json(file) {
        return file.substring(file.length - 5) === ".json";
    }
}