#include "file_explorer.hpp"
#include <algorithm>
#include <cstdio>

namespace gaspardos
{
    namespace desktop
    {
        std::string utf8(uint32_t c)
        {
            std::string s;
            if (c < 128)
                s += static_cast<char>(c);
            else if (c < 2048)
            {
                s += static_cast<char>(0xC0 | (c >> 6));
                s += static_cast<char>(0x80 | (c & 63));
            }
            else if (c < 65536 && !(c >= 0xD800 && c <= 0xDFFF))
            {
                s += static_cast<char>(0xE0 | (c >> 12));
                s += static_cast<char>(0x80 | ((c >> 6) & 63));
                s += static_cast<char>(0x80 | (c & 63));
            }
            else if (c <= 0x10FFFF && c >= 65536)
            {
                s += static_cast<char>(0xF0 | (c >> 18));
                s += static_cast<char>(0x80 | ((c >> 12) & 63));
                s += static_cast<char>(0x80 | ((c >> 6) & 63));
                s += static_cast<char>(0x80 | (c & 63));
            }
            return s;
        }

        static bool decodeUtf8(const std::string& s, std::wstring* out)
        {
            if (out)
                out->clear();
            for (std::size_t i = 0; i < s.size();)
            {
                unsigned char c     = s[i++];
                uint32_t      value = c;
                unsigned      n     = 0;
                if (c >= 0xC2 && c <= 0xDF)
                {
                    value = c & 31;
                    n     = 1;
                }
                else if (c >= 0xE0 && c <= 0xEF)
                {
                    value = c & 15;
                    n     = 2;
                }
                else if (c >= 0xF0 && c <= 0xF4)
                {
                    value = c & 7;
                    n     = 3;
                }
                else if (c >= 128)
                    return false;
                if (i + n > s.size())
                    return false;
                for (unsigned j = 0; j < n; ++j)
                {
                    unsigned char d = s[i++];
                    if ((d & 0xC0) != 0x80)
                        return false;
                    value = (value << 6) | (d & 63);
                }
                if ((n == 1 && value < 128) || (n == 2 && value < 2048) || (n == 3 && value < 65536)
                    || value > 0x10FFFF || (value >= 0xD800 && value <= 0xDFFF))
                    return false;
                if (out)
                    *out += static_cast<wchar_t>(value);
            }
            return true;
        }

        bool toWide(const std::string& s, std::wstring& out)
        {
            return decodeUtf8(s, &out);
        }

        bool validUtf8(const std::string& s)
        {
            return decodeUtf8(s, 0);
        }

        std::string fromUtf16(const uint16_t* text, unsigned length)
        {
            std::string out;
            for (unsigned i = 0; i < length && text[i]; ++i)
            {
                uint32_t c = text[i];
                if (c >= 0xD800 && c <= 0xDBFF)
                {
                    if (i + 1 >= length || text[i + 1] < 0xDC00 || text[i + 1] > 0xDFFF)
                        return "";
                    c = 0x10000 + ((c - 0xD800) << 10) + (text[++i] - 0xDC00);
                }
                else if (c >= 0xDC00 && c <= 0xDFFF)
                    return "";
                out += utf8(c);
            }
            return out;
        }

        std::size_t previousChar(const std::string& s, std::size_t p)
        {
            if (!p)
                return 0;
            --p;
            while (p && (static_cast<unsigned char>(s[p]) & 0xC0) == 0x80)
                --p;
            return p;
        }

        std::size_t nextChar(const std::string& s, std::size_t p)
        {
            if (p >= s.size())
                return s.size();
            ++p;
            while (p < s.size() && (static_cast<unsigned char>(s[p]) & 0xC0) == 0x80)
                ++p;
            return p;
        }

        std::string normalize(const std::string& input)
        {
            if (input.empty() || input == "/" || input == "\\")
                return "";
            std::string p = input;
            std::replace(p.begin(), p.end(), '\\', '/');
            if (p[0] != '/')
                return "";
            std::vector<std::string> parts;
            std::size_t              pos = 1;
            while (pos <= p.size())
            {
                std::size_t end = p.find('/', pos);
                if (end == std::string::npos)
                    end = p.size();
                std::string part = p.substr(pos, end - pos);
                if (part == "..")
                {
                    if (parts.size() > 1)
                        parts.pop_back();
                }
                else if (!part.empty() && part != ".")
                    parts.push_back(part);
                pos = end + 1;
            }
            std::string out;
            for (std::size_t i = 0; i < parts.size(); ++i)
                out += "/" + parts[i];
            return out;
        }

        std::string parentPath(const std::string& path)
        {
            std::string p     = normalize(path);
            std::size_t slash = p.rfind('/');
            return slash == std::string::npos ? "" : p.substr(0, slash);
        }

        std::string fileName(const std::string& path)
        {
            std::string p = normalize(path);
            return p.substr(p.rfind('/') + 1);
        }

        std::string join(const std::string& path, const std::string& name)
        {
            return normalize(path) + "/" + name;
        }

        bool validName(const std::string& name)
        {
            if (name.empty() || name == "." || name == ".." || name.size() > 255)
                return false;
            for (std::size_t i = 0; i < name.size(); ++i)
                if (static_cast<unsigned char>(name[i]) < 32
                    || name.find_first_of("/\\:") != std::string::npos)
                    return false;
            std::wstring wide;
            return toWide(name, wide);
        }

        static std::string failure(const char* text, int64_t code)
        {
            char b[40];
            std::sprintf(b, "%ld", static_cast<long>(code));
            return std::string(text) + " (code " + b + ")";
        }

        static bool ordered(const FileEntry& a, const FileEntry& b)
        {
            if (a.directory != b.directory)
                return a.directory;
            return a.name < b.name;
        }

        DirectoryListing::DirectoryListing(FileAccess& access)
            : access_(access)
            , handle_(-1)
            , memory_(0)
            , idle_(0)
            , closing_(false)
            , loading(false)
            , error(0)
        {
        }

        DirectoryListing::~DirectoryListing()
        {
            if (handle_ >= 0)
                access_.close(handle_);
        }

        void DirectoryListing::cancel()
        {
            if (handle_ >= 0)
            {
                int64_t r = access_.close(handle_);
                if (r < 0)
                {
                    closing_ = true;
                    loading  = true;
                    return;
                }
                handle_ = -1;
            }
            loading  = false;
            closing_ = false;
        }

        bool DirectoryListing::begin(const std::string& path)
        {
            cancel();
            if (handle_ >= 0)
            {
                error = -16;
                return false;
            }
            entries.clear();
            memory_ = 0;
            error   = 0;
            idle_   = 0;
            handle_ = access_.openDirectory(path);
            if (handle_ < 0)
            {
                error = handle_;
                return false;
            }
            path_   = normalize(path);
            loading = true;
            return true;
        }

        bool DirectoryListing::tick()
        {
            if (!loading)
                return false;
            if (closing_)
            {
                int64_t r = access_.close(handle_);
                if (r == 0)
                {
                    handle_  = -1;
                    loading  = false;
                    closing_ = false;
                }
                else if (++idle_ > 3000)
                {
                    error   = r;
                    loading = false;
                }
                return true;
            }
            for (unsigned i = 0; i < 16; ++i)
            {
                FileEntry e;
                int64_t   r = access_.next(handle_, e);
                if (r == -11)
                {
                    if (++idle_ > 3000)
                    {
                        error = -11;
                        cancel();
                    }
                    return true;
                }
                idle_ = 0;
                if (r <= 0)
                {
                    if (r < 0)
                        error = r;
                    std::sort(entries.begin(), entries.end(), ordered);
                    cancel();
                    return true;
                }
                if (e.name == "." || e.name == ".." || !validName(e.name))
                    continue;
                e.path           = join(path_, e.name);
                std::size_t cost = sizeof(FileEntry) + e.path.size() + e.name.size();
                if (entries.size() == 4096 || memory_ + cost > 1048576)
                {
                    error = -27;
                    std::sort(entries.begin(), entries.end(), ordered);
                    cancel();
                    return true;
                }
                memory_ += cost;
                entries.push_back(e);
            }
            return true;
        }

        FileExplorer::FileExplorer(FileAccess& access)
            : access_(access)
            , listing_(access)
            , mode_(OpenFile)
            , overwrite_(false)
            , confirmation_(false)
            , finished_(false)
            , accepted_(false)
            , selected_(-1)
        {
        }

        void FileExplorer::begin(Mode mode, const std::string& initial, bool overwrite)
        {
            mode_      = mode;
            overwrite_ = overwrite;
            finished_ = accepted_ = confirmation_ = false;
            confirmationPath_.clear();
            result_.clear();
            volumes = access_.roots();
            FileEntry   info;
            std::string path = normalize(initial);
            if (!path.empty() && access_.stat(path, info) == 0 && !info.directory)
                path = parentPath(path);
            if (!navigate(path))
                navigate("");
        }

        bool FileExplorer::navigate(const std::string& path)
        {
            std::string next = normalize(path);
            if (!path.empty() && next.empty() && path != "/" && path != "\\")
            {
                message = "Chemin absolu requis";
                return false;
            }
            if (next.empty())
            {
                listing_.cancel();
                if (listing_.loading)
                {
                    message = "Fermeture du dossier en cours";
                    return false;
                }
                listing_.entries = volumes;
                directory_.clear();
                selected_     = -1;
                confirmation_ = false;
                message       = "Ordinateur : choisir un volume";
                return true;
            }
            FileEntry info;
            int64_t   r = access_.stat(next, info);
            if (r < 0 || !info.directory)
            {
                message = failure("Dossier inaccessible", r < 0 ? r : -20);
                return false;
            }
            if (!listing_.begin(next))
            {
                message = failure("Ouverture du dossier", listing_.error);
                return false;
            }
            directory_    = next;
            selected_     = -1;
            confirmation_ = false;
            message       = "Lecture du dossier...";
            return true;
        }

        bool FileExplorer::tick()
        {
            bool changed = listing_.tick();
            if (changed && !listing_.loading)
            {
                message = listing_.error ? failure("Lecture incomplete", listing_.error)
                                         : "Selectionner un dossier ou un fichier";
            }
            return changed;
        }

        void FileExplorer::select(int index)
        {
            if (listing_.loading || index < 0
                || static_cast<std::size_t>(index) >= entries().size())
                return;
            selected_     = index;
            confirmation_ = false;
        }

        void FileExplorer::activate(int index)
        {
            select(index);
            if (selected_ < 0 || listing_.loading)
                return;
            const FileEntry e = entries()[selected_];
            if (e.directory)
                navigate(e.path);
            else if (mode_ != SelectFolder)
                accept(e.name);
        }

        bool FileExplorer::accept(const std::string& name)
        {
            if (listing_.loading)
            {
                message = "Attendre la lecture du dossier";
                return false;
            }
            std::string path;
            if (mode_ == SelectFolder)
            {
                path = directory_;
                if (selected_ >= 0 && entries()[selected_].directory)
                    path = entries()[selected_].path;
                if (path.empty())
                {
                    message = "Choisir un dossier sur un volume";
                    return false;
                }
            }
            else
            {
                if (directory_.empty() || !validName(name))
                {
                    message = "Nom de fichier simple requis";
                    return false;
                }
                path = join(directory_, name);
            }
            FileEntry info;
            int64_t   r = access_.stat(path, info);
            if (mode_ == SelectFolder || mode_ == OpenFile)
            {
                if (r < 0)
                {
                    message = failure("Selection inaccessible", r);
                    return false;
                }
                if (mode_ == OpenFile && info.directory)
                {
                    navigate(path);
                    return false;
                }
                if (mode_ == SelectFolder && !info.directory)
                {
                    message = "Choisir un dossier";
                    return false;
                }
            }
            else
            {
                if (r == 0)
                {
                    if (info.directory)
                    {
                        navigate(path);
                        return false;
                    }
                    if (!overwrite_)
                    {
                        message = "Ce fichier existe : choisir un autre nom";
                        return false;
                    }
                    if (!confirmation_ || confirmationPath_ != path)
                    {
                        confirmation_     = true;
                        confirmationPath_ = path;
                        message           = "Fichier existant : cliquer Remplacer pour confirmer";
                        return false;
                    }
                }
                else if (r != -2)
                {
                    message = failure("Destination inaccessible", r);
                    return false;
                }
            }
            result_   = path;
            accepted_ = finished_ = true;
            listing_.cancel();
            return true;
        }

        bool FileExplorer::createFolder(const std::string& name)
        {
            if (directory_.empty() || listing_.loading || !validName(name))
            {
                message = "Saisir un nom simple dans un dossier";
                return false;
            }
            std::string path = join(directory_, name);
            int64_t     r    = access_.mkdir(path);
            if (r < 0)
            {
                message = failure("Creation du dossier", r);
                return false;
            }
            return navigate(path);
        }

        void FileExplorer::cancel()
        {
            listing_.cancel();
            finished_ = true;
            accepted_ = false;
        }

        DirectoryTree::DirectoryTree(FileAccess& access) : access_(access), listing_(access)
        {
        }

        void DirectoryTree::append(const FileEntry& entry, unsigned depth)
        {
            if (rows.size() >= 4096 || depth > 32)
                return;
            TreeRow row;
            row.entry    = entry;
            row.depth    = depth;
            row.expanded = expanded_.count(entry.path) != 0;
            rows.push_back(row);
            if (row.expanded)
            {
                std::map<std::string, std::vector<FileEntry> >::const_iterator it =
                    children_.find(entry.path);
                if (it != children_.end())
                    for (std::size_t i = 0; i < it->second.size(); ++i)
                        append(it->second[i], depth + 1);
            }
        }

        void DirectoryTree::rebuild()
        {
            rows.clear();
            if (root_.empty())
                return;
            FileEntry e;
            e.path      = root_;
            e.name      = fileName(root_);
            e.directory = true;
            append(e, 0);
        }

        bool DirectoryTree::open(const std::string& path)
        {
            FileEntry   e;
            std::string root = normalize(path);
            int64_t     r    = access_.stat(root, e);
            if (r < 0 || !e.directory)
            {
                message = "Dossier inaccessible";
                return false;
            }
            if (!listing_.begin(root))
            {
                message = "Impossible de lire le dossier";
                return false;
            }
            root_ = loadingPath_ = root;
            children_.clear();
            expanded_.clear();
            expanded_.insert(root);
            rebuild();
            message = "Lecture de l'arborescence";
            return true;
        }

        void DirectoryTree::toggle(std::size_t index)
        {
            if (index >= rows.size() || !rows[index].entry.directory || listing_.loading)
                return;
            std::string path = rows[index].entry.path;
            if (expanded_.count(path))
                expanded_.erase(path);
            else
            {
                expanded_.insert(path);
                if (!children_.count(path))
                {
                    if (!listing_.begin(path))
                    {
                        expanded_.erase(path);
                        message = "Dossier inaccessible";
                        return;
                    }
                    loadingPath_ = path;
                }
            }
            rebuild();
        }

        bool DirectoryTree::tick()
        {
            if (!listing_.tick())
                return false;
            if (!listing_.loading)
            {
                if (listing_.error)
                {
                    message = failure("Arborescence incomplete", listing_.error);
                    expanded_.erase(loadingPath_);
                }
                else
                {
                    std::size_t memory = 0;
                    for (std::size_t i = 0; i < listing_.entries.size(); ++i)
                        memory += sizeof(FileEntry) + listing_.entries[i].path.size()
                                  + listing_.entries[i].name.size();
                    for (std::map<std::string, std::vector<FileEntry> >::const_iterator folder =
                             children_.begin();
                         folder != children_.end();
                         ++folder)
                        for (std::size_t i = 0; i < folder->second.size(); ++i)
                            memory += sizeof(FileEntry) + folder->second[i].path.size()
                                      + folder->second[i].name.size();
                    if (memory > 2097152)
                    {
                        expanded_.erase(loadingPath_);
                        message = "Limite du cache : cliquer Actualiser pour liberer";
                    }
                    else
                    {
                        children_[loadingPath_] = listing_.entries;
                        message                 = "Arborescence chargee";
                    }
                }
                rebuild();
            }
            return true;
        }

        bool saveFile(FileAccess&        access,
                      const std::string& path,
                      const std::string& data,
                      bool               overwrite,
                      std::string&       message)
        {
            FileEntry entry;
            int64_t   exists = access.stat(path, entry);
            if (exists == 0 && (entry.directory || !overwrite))
            {
                message = "Destination existante";
                return false;
            }
            if (exists != 0 && exists != -2)
            {
                message = "Destination inaccessible";
                return false;
            }
            std::string temporary = path + ".gaspardedit.tmp", backup = path + ".gaspardedit.bak";
            if (exists == 0 && access.stat(backup, entry) != -2)
            {
                message = "Sauvegarde .gaspardedit.bak existante/inaccessible";
                return false;
            }
            int64_t r = access.create(temporary, data);
            if (r < 0)
            {
                message = failure("Creation/ecriture .gaspardedit.tmp impossible", r);
                return false;
            }
            if (exists == 0)
            {
                r = access.rename(path, backup);
                if (r < 0)
                {
                    access.remove(temporary);
                    message = "Original conserve, sauvegarde impossible";
                    return false;
                }
            }
            r = access.rename(temporary, path);
            if (r < 0)
            {
                int64_t restored = exists == 0 ? access.rename(backup, path) : 0;
                if (restored < 0)
                    message =
                        "Echec : original dans .gaspardedit.bak, nouveau dans .gaspardedit.tmp";
                else
                {
                    access.remove(temporary);
                    message = "Echec d'enregistrement; original conserve";
                }
                return false;
            }
            message = "Fichier enregistre";
            if (exists == 0 && access.remove(backup) < 0)
                message += "; ancien contenu conserve en .gaspardedit.bak";
            return true;
        }
    }  // namespace desktop
}  // namespace gaspardos
