import { app } from "./app.js";
import { EventHandler } from "./event-handler.js";

export class Container extends EventHandler{ 
    status = "unknown"
    cpus = 0
    memory = "0m"
    image = "unknown:unknown"
    name = null 
    channelUid = null 
    log = false 
    bytesSent = 0
    bytesReceived = 0
    _container = null
    render(el){
        if(this._container == null){
        this._container = el
        this.terminal.open(this._container)
        

        this.terminal.onData(data => {
            if (this.ws && this.ws.readyState === WebSocket.OPEN) {
                this.ws.send(data);
            }
        });
            
        }
        this.refresh()
        this.terminal.focus()
    }
    refresh(){
        //this._fitAddon.fit();
        this.ws.send("\x0C");
    }
    toggle(){
        this._container.classList.toggle("hidden")
        this.refresh()
    }

    constructor(channelUid,log){
        super()
        this.terminal = new Terminal({ cursorBlink: true ,theme: {
    background: 'rgba(0, 0, 0, 0)', // Fully transparent
  }
 });
        this._fitAddon = new FitAddon.FitAddon();
        this.terminal.loadAddon(this._fitAddon);
        window.addEventListener("resize", () => this._fitAddon.fit());
        this.log = log ? true : false 
        this.channelUid = channelUid    
        this.update()
        this.addEventListener("stdout", (data) => {
            this.bytesReceived += data.length
            if(this.log){
                console.log(`Container ${this.name}: ${data}`)
            }
            const fixedData = new Uint8Array(data);
            this.terminal.write(new TextDecoder().decode(fixedData));

        })
        this.ws = new WebSocket(`/container/sock/${channelUid}.json`)
        this.ws.binaryType = "arraybuffer";  // Support binary data
        this.ws.onmessage = (event) => {
            this.emit("stdout", event.data)
        }
        this.ws.onopen = () => {
            this.refresh()
        }
        window.container = this 

    }
    async start(){
        const result = await app.rpc.startContainer(this.channelUid)
        await this.refresh()
        return result && this.status == 'running'
    }
    async stop(){
        const result = await app.rpc.stopContainer(this.channelUid)
        await this.refresh()
        return result && this.status == 'stopped'
    }
    async write(data){
        await this.ws.send(data)
        this.bytesSent += data.length
        return true
    }
    async update(){
        
        const container = await app.rpc.getContainer(this.channelUid)
        this.status = container["status"]
        this.cpus = container["cpus"]
        this.memory = container["memory"]
        this.image = container["image"]
        this.name = container["name"]
    }

}
/*
window.getContainer = function(){
    return new Container(app.channelUid)
}*/

