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

namespace gaspardos
{
    namespace desktop
    {
        static bool nativePath(const std::string& path, std::wstring& wide)
        {
            std::string normalized = normalize(path);
            if (normalized.empty() || normalized.size() > 4095 || !toWide(normalized, wide))
                return false;
            for (std::size_t i = 0; i < wide.size(); ++i)
            {
                if (wide[i] < 32)
                    return false;
                if (wide[i] == '/')
                    wide[i] = '\\';
            }
            // Volume roots need a trailing separator for the GaspardFS wrapper.
            if (parentPath(normalized).empty())
                wide += L"\\";
            return true;
        }

        static void convert(const GO64_FSInfo& info, FileEntry& entry)
        {
            entry.name      = fromUtf16(info.name, std::min<unsigned>(128, info.name_length));
            entry.directory = info.is_directory != 0;
            entry.bytes     = info.bytes;
        }

        std::vector<FileEntry> NativeFileAccess::roots()
        {
            std::vector<FileEntry> result;
            const char*            prefixes[] = { "AHCIDISK", "IDEDISK", "USBDISK" };
            const unsigned         counts[]   = { 32, 20, 8 };
            for (unsigned kind = 0; kind < 3; ++kind)
                for (unsigned i = 0; i < counts[kind]; ++i)
                {
                    char name[32];
                    std::sprintf(name, "/%s%u", prefixes[kind], i);
                    FileEntry entry;
                    if (stat(name, entry) == 0 && entry.directory)
                    {
                        entry.name = name + 1;
                        entry.path = name;
                        result.push_back(entry);
                    }
                }
            return result;
        }

        int64_t NativeFileAccess::stat(const std::string& path, FileEntry& entry)
        {
            std::wstring wide;
            if (!nativePath(path, wide))
                return -22;
            GO64_FSInfo info;
            int64_t     r = GO64_fs_stat(wide.c_str(), &info);
            if (r == 0)
            {
                convert(info, entry);
                entry.path = normalize(path);
                entry.name = fileName(path);
            }
            return r;
        }

        int64_t NativeFileAccess::openDirectory(const std::string& path)
        {
            std::wstring wide;
            return nativePath(path, wide) ? GO64_fs_open(wide.c_str(), GO64_RDONLY) : -22;
        }

        int64_t NativeFileAccess::next(int64_t handle, FileEntry& entry)
        {
            GO64_FSInfo info;
            int64_t     r = GO64_fs_readdir(handle, &info);
            if (r == 1)
                convert(info, entry);
            return r;
        }

        int64_t NativeFileAccess::close(int64_t handle)
        {
            return GO64_fs_close(handle);
        }

        int64_t NativeFileAccess::mkdir(const std::string& path)
        {
            std::wstring wide;
            return nativePath(path, wide) ? GO64_fs_mkdir(wide.c_str()) : -22;
        }

        int64_t NativeFileAccess::read(const std::string& path,
                                       std::string&       data,
                                       std::size_t        limit)
        {
            std::wstring wide;
            if (!nativePath(path, wide))
                return -22;
            NativeFile file;
            int64_t    r = file.open(wide.c_str(), GO64_RDONLY);
            if (r < 0)
                return r;
            data.clear();
            char buffer[8192];
            for (;;)
            {
                r = file.read(buffer, sizeof(buffer));
                if (r < 0)
                    return r;
                if (!r)
                    break;
                if (static_cast<uint64_t>(r) > limit - data.size())
                    return -27;
                data.append(buffer, static_cast<std::size_t>(r));
            }
            return file.close();
        }

        int64_t NativeFileAccess::create(const std::string& path, const std::string& data)
        {
            std::wstring wide;
            if (!nativePath(path, wide))
                return -22;
            NativeFile file;
            int64_t    r = file.open(wide.c_str(), GO64_WRONLY | GO64_CREAT | GO64_EXCL);
            if (r < 0)
                return r;
            std::size_t offset = 0;
            while (offset < data.size())
            {
                r = file.write(data.data() + offset,
                               std::min<std::size_t>(8192, data.size() - offset));
                if (r <= 0)
                {
                    if (file.close() == 0)
                        GO64_fs_unlink(wide.c_str());
                    return r < 0 ? r : -5;
                }
                offset += static_cast<std::size_t>(r);
            }
            return file.close();
        }

        int64_t NativeFileAccess::rename(const std::string& from, const std::string& to)
        {
            std::wstring a, b;
            return nativePath(from, a) && nativePath(to, b) ? GO64_fs_rename(a.c_str(), b.c_str())
                                                            : -22;
        }

        int64_t NativeFileAccess::remove(const std::string& path)
        {
            std::wstring wide;
            return nativePath(path, wide) ? GO64_fs_unlink(wide.c_str()) : -22;
        }
    }  // namespace desktop
}  // namespace gaspardos
