local system = require 'system'
local asio_error = require 'asio_error'
local libc_service = require 'libc_service'
local easybox = require 'easybox'
local fs = require 'filesystem'
local stream = require 'stream'
local unix = require 'unix'
local qt = require 'qt6'

local qml = qt.load_qml('qrc:/main.qml')

local function supervise(master)
    local qt_root = system.environment.EMILUA_DEMO_QT_ROOT or '/usr/lib'
    local access_paths = {
        ['/usr/lib'] = 0,
        ['/usr/lib/qt6/plugins'] = 0,
        [qt_root] = 0,
        [qt_root .. '/qt6/plugins'] = 0,
    }

    spawn(function()
        while true do
            local ok, err = pcall(function() master:receive() end)
            if not ok then
                if err == asio_error.misc.eof then
                    break
                end
                error(err)
            end

            if master.function_ == 'access' then
                local path = tostring(master:arguments())
                if access_paths[path] ~= nil then
                    master:send(access_paths[path])
                else
                    -- This is only an existence check, not permission to open.
                    -- The sandbox's OS restrictions still apply to the fallback.
                    master:use_slave_credentials()
                end
            else
                master:use_slave_credentials()
            end
        end
    end):detach()
end

local function decode(path)
    -- A fresh libc_service is required for each child because the slave end is
    -- consumed when the actor is spawned.
    local master, slave = libc_service.new()
    supervise(master)

    -- emilua-genmain embeds init.lua and decoder.lua in this executable, and the
    -- child inherits that source cache. emilua-genmods also embeds the selected
    -- native modules. Neither Lua nor native code needs a general filesystem.
    local worker = easybox.new{
        module = './decoder',
        libc_service = slave,
        stdout = 'share',
        stderr = 'share',
    }

    local host_channel, worker_channel = unix.seqpacket.socket.pair()
    worker_channel = worker_channel:release()
    local input = fs.open(fs.path.new(path), {'read_only'})

    -- The worker gets the selected read-only file and one framed reply socket.
    worker:send{ input = input, output = worker_channel }
    input:close()
    worker_channel:close()

    local buf = byte_span.new(1024)
    local nread, fds = host_channel:receive_with_fds(buf, 1)
    host_channel:close()
    local message = tostring(buf:first(nread))

    if message:match('^ERROR\n') then
        error(message:sub(#'ERROR\n' + 1))
    end

    local width, height, format = message:match('^OK\n(%d+)\n(%d+)\n([%w_]+)$')
    assert(width and fds[1], 'invalid decoder response')
    return {
        width = tonumber(width),
        height = tonumber(height),
        format = format,
        memfd = fds[1],
    }
end

local function show_decoded(path)
    local result = decode(path)
    local image = qt.image_from_decode_result(result)
    result.memfd:close()
    qml.property.img.image = image
    qml.property.status.text = string.format(
        'Decoded in a separate process: %d x %d, %s',
        result.width, result.height, result.format)
    return result
end

local cli_image
local quit_after_decode
for i = 2, #system.arguments do
    if system.arguments[i] == '--' then
        cli_image = system.arguments[i + 1]
        quit_after_decode = system.arguments[i + 2] == '--quit'
        break
    end
end

if cli_image then
    local ok, result = pcall(show_decoded, cli_image)
    if not ok then
        stream.write_all(system.err, 'Decode failed: ' .. tostring(result) .. '\n')
        system.exit(1)
        return
    end
    print(string.format(
        'Decoded in a separate process: %d x %d, %s',
        result.width, result.height, result.format))
    if quit_after_decode then
        system.exit()
    end
else
    qml.property.fileDialog['accepted()'] = function()
        spawn(function()
            local path = tostring(qml.property.fileDialog.selectedFile)
            path = string.sub(path, 1 + #'file://')
            local ok, err = pcall(show_decoded, path)
            if not ok then
                qml.property.status.text = 'Decode failed: ' .. tostring(err)
            end
        end):detach()
    end
    qml.object['visibleChanged(bool)'] = function(visible)
        if not visible then
            spawn(function() system.exit() end):detach()
        end
    end
    qml.engine['quit()'] = function()
        spawn(function() system.exit() end):detach()
    end
    qml.object('show()')
    qml.property.fileDialog('open()')
end
