assert(_VERSION == "Lua 5.4")

package.path = "lualib/?.lua;skynet/lualib/?.lua;simulation/?.lua"
package.cpath = "skynet/luaclib/?.so;luaclib/?.so"

local auth = require "auth"
local ok, atoken = pcall(auth)
if not ok then
    print("please check: login auth err", atoken)
    return
end

local dump = require "dump"
local termfx = require "termfx"
local ui = require "simpleui"

termfx.init()
termfx.inputmode(termfx.input.ALT + termfx.input.MOUSE)
termfx.outputmode(termfx.output.COL256)

local function main(token)
    local sock = require ("network")()
    local sok = sock:connect(token.ip, token.port)
    assert(sok)

    local output = {}

    local mok, err = pcall(function()
        local msg_list = {}
        local input
        local string = {}

        while true do
            termfx.clear(termfx.color.WHITE, termfx.color.BLACK)

            local w, h = termfx.size()
            local width = math.floor(w / 2)

            ui.box(2, 2, width, h - 10)
            ui.box(w / 2, 2, width, h - 10)

            termfx.printat(2, h - 1, input)
            termfx.printat(2, h, table.concat(string, ""))
            termfx.present()


            local evt = termfx.pollevent(100)
            if evt then
                if evt.type == 'key' then
                    if evt.key == termfx.key.CTRL_C then
                        break
                    elseif evt.key == termfx.key.BACKSPACE2 then
                        table.remove(string)
                    elseif evt.key == termfx.key.ENTER then
                        input = table.concat(string, '')
                        string = {}
                        pcall(act_when_input, input)
                    elseif evt.key == termfx.key.SPACE then
                        table.insert(string, ' ')
                    else
                        table.insert(string, evt.char)
                    end
                end
            else
                local success, err = sock:update()
                assert(success, err)

                local r, msgid, msg = recv_msg()
                if r == true then
                    table.insert(msg_list, {MN[msgid] or msgid, dump(msg)})
                elseif r == false then
                    p('网络断开，结束客户端', msgid)
                    break
                end
            end
        end
    end)

    termfx.shutdown()
    if not mok then
        print("Error: ", err)
    end
    print(':\n', table.concat(output, '\n'))
end

main(atoken)
