import TilorswiftFieldClickedEvent from "./events/TilorswiftFieldClickedEvent.js";
import TilorswiftFieldEnteredEvent from "./events/TilorswiftFieldEnteredEvent.js";

export default class Field
{
    constructor(tileset, x = 0, y = 0, index = -1)
    {
        this.tileset = tileset;
        this.index = index;
        this.x = x;
        this.y = y;
        this.isEntrancePoint = false;
        this.isTargetPoint = false;
        this.initHtml();
        this.initEventListeners();
    }

    initEventListeners()
    {
        this.htmlElement.addEventListener(
            'mousedown', (event) => {
                window.dispatchEvent(new TilorswiftFieldClickedEvent(this, event.button));
            }
        );

        this.htmlElement.addEventListener(
            'contextmenu', (event) => {
                window.dispatchEvent(new TilorswiftFieldClickedEvent(this), event.button);
            }
        );

        this.htmlElement.addEventListener(
            'mouseenter', () => {
                window.dispatchEvent(new TilorswiftFieldEnteredEvent(this));
            }
        );
    }

    initHtml()
    {
        this.htmlElement = document.createElement('td');
        this.className = 'field';
        this.setupElement();
        this.addSelector();
    }

    setupElement()
    {
        this.htmlElement.classList.add(this.className);
        this.htmlElement.style.width = String(this.tileset.getTileWidth()) + 'px';
        this.htmlElement.style.height = String(this.tileset.getTileHeight()) + 'px';
        this.htmlElement.style.backgroundSize = 'auto ' + this.tileset.getTileHeight() + 'px';
        this.htmlElement.style.backgroundImage = 'url("' + this.tileset.image.src + '")';
        this.htmlElement.style.backgroundPositionX = -this.index * this.tileset.getTileWidth() + 'px';
    }

    addSelector()
    {
        let hoverElement = document.createElement('div');
        hoverElement.classList.add('selection');
        this.htmlElement.appendChild(hoverElement);
    }

    setIndex(index)
    {
        this.index = index;
        this.htmlElement.style.backgroundPositionX = -this.index * this.tileset.getTileWidth() + 'px';
    }

    setEntrancePoint(bool)
    {
        this.isEntrancePoint = bool;

        if (this.isEntrancePoint) {
            this.htmlElement.classList.add('entrance');
        } else {
            this.htmlElement.classList.remove('entrance');
        }
    }

    setTargetPoint(bool)
    {
        this.isTargetPoint = bool;

        if (this.isTargetPoint) {
            this.htmlElement.classList.add('target');
        } else {
            this.htmlElement.classList.remove('target');
        }
    }

    getElement()
    {
        return this.htmlElement;
    }
}
