
use utils
use fs

+ class Context {
    ~ method: utils:ByteBufferStrRef
    ~ path: utils:ByteBufferStrRef
    ~ query_string: utils:ByteBufferStrRef
    - header_data: utils:ByteBufferStrRef
    - body_data: utils:ByteBufferStrRef
    - chunks: utils:ByteBuffer (utils:ByteBuffer.new(8192))

    ~ status: uint (0)
    - stage: uint (0)
    ~ parsed_index: uint (0)
    ~ content_length: uint (0)
    ~ body_received: uint (0)
    - save_to_file: ?fs:FileStream (null)

    ~ has_host: bool (false)
    ~ chunked: bool (false)
    - done: bool (false)

    use ContextParser

    static fn new(buffer: utils:ByteBuffer) Context {
        return Context {
            method: buffer.str_ref(0, 0)
            path: buffer.str_ref(0, 0)
            query_string: buffer.str_ref(0, 0)
            header_data: buffer.str_ref(0, 0)
            body_data: buffer.str_ref(0, 0)
        }
    }

    fn reset() {
        let file = this.save_to_file
        if isset(file) : file.close()
        this.save_to_file = null

        this.stage = 0
        this.status = 0

        this.method.clear()
        this.path.clear()
        this.query_string.clear()
        this.header_data.clear()
        this.body_data.clear()
        this.chunks.clear()

        this.reset_cache()

        this.has_host = false
        this.chunked = false
        this.done = false
    }

    + get body : String {
        if !this.done : return ""
        if this.chunked : return this.chunks.to_string()
        return this.body_data
    }
}
