import FileLoader from "./FileLoader.js";
import Terrain from "../tilorswift/js/Terrain.js";
import {FullscreenEffectFactory} from "./effects/FullscreenEffectFactory.js";

export default class Level
{
    static FACTOR_GRAVITY = 4.903;

    /**
     * @param {Terrain} terrain 
     */
    constructor(terrain)
    {
        /** @type {Terrain} */
        this.terrain = terrain;

	    this.fullscreenEffects = [];
        this.gravity = 2.0;
    }

    getTilesetId()
    {
        return this.terrain.tileset.setId;
    }

    getBackgroundColor()
    {
        return this.terrain.backgroundColor;
    }

    getBackgroundImage()
    {
        return this.terrain.backgroundImage;
    }

    getRows()
    {
        return this.terrain.tilesY;
    }

    getColumns()
    {
        return this.terrain.tilesX;
    }

    getStartX()
    {
        return this.terrain.entranceTileX;
    }

    getStartY()
    {
        return this.terrain.entranceTileY;
    }

    getTargetX()
    {
        return this.terrain.targetTileX;
    }

    getTargetY()
    {
        return this.terrain.targetTileY;
    }

    getTilesetMatrix()
    {
        return this.terrain.fields;
    }

    hasEntrancePoint()
    {
        return this.terrain.hasEntrancePoint();
    }

    hasTargetPoint()
    {
        return this.terrain.hasTargetPoint();
    }

    setGravity(gravity)
    {
        this.gravity = gravity;
    }

    static createFromFile(filename, onLoad = () => {})
    {
        let loader = new FileLoader(filename);
        loader.onLoad = (data) => {
            const json = JSON.parse(data);
            const level = new Level(Terrain.createFromJson(json));
            level.setGravity(json.gravity / Level.FACTOR_GRAVITY);

            for (const oldEffect of level.fullscreenEffects) {
               oldEffect.destroy();
	        }

            level.fullscreenEffects = [];

            if (json.hasOwnProperty('effects')) {
               const effectFactory = new FullscreenEffectFactory();

               for (const effect of json.effects) {
                   level.fullscreenEffects.push(
                       effectFactory.getEffect(effect)
                   );
               }
            }

            onLoad(level);
        }
        loader.loadContent();
    }

    static createFromJson(json)
    {
        const data = JSON.parse(json);

        const terrain = Terrain.createFromJson(data);
        const level = new Level(terrain);
        level.setGravity(data.gravity / Level.FACTOR_GRAVITY);

        for (const oldEffect of level.fullscreenEffects) {
           oldEffect.destroy();
	    }

        level.fullscreenEffects = [];

	if (data.hasOwnProperty('effects')) {
		const effectFactory = new FullscreenEffectFactory();

		for (const effect of data.effects) {
			level.fullscreenEffects.push(
				effectFactory.getEffect(effect)
			);
		}
	}

        return level;
    }
}
