#include "native.hpp"
#include <cstdio>

namespace terminal
{
    NativeBackend::NativeBackend(Output& output)
        : output_(output)
        , listing_(access_)
        , offset_(0)
        , listed_(0)
        , printListing_(false)
        , readError_(false)
        , phase_(Idle)
        , children_(0)
    {
        // The language starts at the virtual mount root.
        (void)GO64_process_chdir("/");
    }

    void NativeBackend::message(const std::string& text)
    {
        output_.print(text + "\n");
    }

    int NativeBackend::directory(const std::string& path)
    {
        gaspardos::desktop::FileEntry entry;
        int64_t                       result = access_.stat(path, entry);
        return result < 0 ? static_cast<int>(result) : entry.directory ? 0 : -20;
    }

    int NativeBackend::changeDirectory(const std::string& path)
    {
        int64_t result = GO64_process_chdir(path.c_str());
        if (result == -38) return path == "/" ? 0 : directory(path);
        return static_cast<int>(result);
    }

    bool NativeBackend::busy() const
    {
        return phase_ != Idle || listing_.loading || printListing_;
    }

    unsigned NativeBackend::children() const
    {
        return children_;
    }

    int NativeBackend::list(const std::string& path)
    {
        if (busy())
            return -16;
        if (path == "/")
        {
            std::vector<gaspardos::desktop::FileEntry> roots = access_.roots();
            for (std::size_t i = 0; i < roots.size(); ++i)
                message("[D] " + roots[i].path);
            if (roots.empty())
                message("No mounted volume");
            return 0;
        }
        int result = directory(path);
        if (result != 0)
            return result;
        if (!listing_.begin(path))
            return static_cast<int>(listing_.error);
        listed_       = 0;
        printListing_ = true;
        return 0;
    }

    int NativeBackend::launch(const std::string& path, const Arguments& arguments)
    {
        if (busy())
            return -16;
        if (arguments.empty() || arguments.size() > 20)
            return -22;
        std::size_t argumentBytes = 0;
        for (std::size_t i = 0; i < arguments.size(); ++i)
        {
            if (arguments[i].size() > 1023)
                return -22;
            argumentBytes += arguments[i].size() + 1;
        }
        if (argumentBytes > 8192)
            return -22;
        gaspardos::desktop::FileEntry entry;
        int64_t                       result = access_.stat(path, entry);
        if (result != 0)
            return static_cast<int>(result);
        if (entry.directory)
            return -21;
        if (entry.bytes < 64 || entry.bytes > 4u * 1024u * 1024u)
            return -27;
        std::wstring wide;
        if (!gaspardos::desktop::toWide(path, wide))
            return -22;
        for (std::size_t i = 0; i < wide.size(); ++i)
            if (wide[i] == '/')
                wide[i] = '\\';
        result = image_.open(wide.c_str(), GO64_RDONLY);
        if (result < 0)
            return static_cast<int>(result);
        bytes_.resize(static_cast<std::size_t>(entry.bytes));
        arguments_  = arguments;
        executable_ = path;
        offset_     = 0;
        phase_      = Reading;
        message("Loading " + path);
        return 0;
    }

    void NativeBackend::cancel()
    {
        listing_.cancel();
        printListing_ = false;
        if (image_.handle() >= 0)
            phase_ = Failed;
        else
        {
            phase_ = Idle;
            bytes_.clear();
            arguments_.clear();
        }
    }

    void NativeBackend::tick()
    {
        char    output[4096];
        int64_t received = GO64_process_read(output, sizeof(output));
        if (received > 0 && received <= static_cast<int64_t>(sizeof(output)))
            output_.print(std::string(output, static_cast<std::size_t>(received)));
        else if (received < 0 && received != -11 && received != -38 && !readError_)
        {
            message("Child console read failed");
            readError_ = true;
        }
        int64_t children = GO64_process_status();
        if (children >= 0)
            children_ = static_cast<unsigned>(children);
        if (listing_.loading)
            listing_.tick();
        if (printListing_ && !listing_.loading)
        {
            for (unsigned budget = 0; budget < 8 && listed_ < listing_.entries.size();
                 ++budget, ++listed_)
            {
                const gaspardos::desktop::FileEntry& entry = listing_.entries[listed_];
                char                                 size[48];
                std::sprintf(size, "%llu", static_cast<unsigned long long>(entry.bytes));
                message(std::string(entry.directory ? "[D] " : "[F] ") + entry.name
                        + (entry.directory ? "" : "  " + std::string(size) + " bytes"));
            }
            if (listed_ == listing_.entries.size())
            {
                if (listing_.error)
                    message("Directory listing failed or truncated");
                printListing_ = false;
            }
        }
        if (phase_ == Reading)
        {
            std::size_t count  = std::min<std::size_t>(16384, bytes_.size() - offset_);
            int64_t     result = image_.read(&bytes_[offset_], count);
            if (result == -11)
                return;
            if (result <= 0 || static_cast<uint64_t>(result) > count)
            {
                message("Cannot read complete executable");
                phase_ = Failed;
                return;
            }
            offset_ += static_cast<std::size_t>(result);
            if (offset_ == bytes_.size())
                phase_ = Closing;
        }
        if (phase_ == Closing || phase_ == Failed)
        {
            int64_t result = image_.close();
            if (result < 0)
                return;
            if (phase_ == Failed)
            {
                bytes_.clear();
                arguments_.clear();
                phase_ = Idle;
                return;
            }
            phase_ = Spawning;
        }
        if (phase_ == Spawning)
        {
            std::vector<const char*> pointers;
            for (std::size_t i = 0; i < arguments_.size(); ++i)
                pointers.push_back(arguments_[i].c_str());
            int64_t result =
                GO64_process_spawn(&bytes_[0], bytes_.size(), pointers.size(), &pointers[0]);
            if (result == -11)
                return;
            if (result < 0)
            {
                char error[80];
                std::sprintf(error, "Launch failed (%lld)", static_cast<long long>(result));
                message(error);
                if (result == -38)
                    message("Kernel process extension (150-152) is required");
            }
            else
            {
                char info[80];
                std::sprintf(info, "Started task %lld", static_cast<long long>(result));
                message(info);
            }
            std::vector<char>().swap(bytes_);
            arguments_.clear();
            phase_ = Idle;
        }
    }
}  // namespace terminal
