/*
    Hurry Curry! - a game about cooking
    Copyright (C) 2026 Hurry Curry! Contributors

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, version 3 of the License only.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

*/

import { canvas, player_controller, send } from "./main.ts";
import { System } from "./system.ts";

const KEY_CHAT = "Enter"
const KEY_CLOSE = "Escape"

export class SChat extends System {
    chat: null | HTMLInputElement = null;

    override input(ev: KeyboardEvent, down: boolean): boolean {
        if (this.chat) {
            this.chat.focus()
            return true
        } else if (down && ev.code == KEY_CHAT) {
            this.open()
        }
        return false
    }

    open() {
        this.chat = document.createElement("input")
        this.chat.type = "text"
        this.chat.placeholder = "Message"
        document.body.append(this.chat)
        this.chat.addEventListener("keydown", ev => {
            if (ev.code == KEY_CLOSE) {
                this.close()
                ev.preventDefault()
            }
            if (ev.code == KEY_CHAT) {
                this.submit()
                ev.preventDefault()
            }
        })
        this.chat.focus()
    }
    close() {
        if (!this.chat) return
        this.chat.remove()
        this.chat = null;
        canvas.focus()
    }
    submit() {
        if (this.chat) {
            if (this.chat.value.length) send({ player: player_controller.my_id!, type: "communicate", message: { text: this.chat.value } })
            setTimeout(() => this.close(), 0)
        } else {
            this.open()
        }
    }
}
