#include "code_buffer.hpp"
#include <algorithm>

namespace gaspardos
{
    namespace desktop
    {
        CodeBuffer::CodeBuffer() : cursor_(0), undoBytes_(0), crlf_(false), bom_(false)
        {
            index();
        }

        void CodeBuffer::index()
        {
            lines_.clear();
            lines_.push_back(0);
            for (std::size_t i = 0; i < text_.size(); ++i)
                if (text_[i] == '\n')
                    lines_.push_back(i + 1);
        }

        bool CodeBuffer::load(const std::string& raw, std::string& error)
        {
            if (raw.size() > 1048576 || raw.find('\0') != std::string::npos)
            {
                error = "Fichier binaire ou superieur a 1 Mio";
                return false;
            }
            if (!validUtf8(raw))
            {
                error = "Texte UTF-8/ASCII requis (UTF-16 non supporte)";
                return false;
            }
            std::string normalized;
            bool        bom = raw.compare(0, 3, "\xEF\xBB\xBF") == 0, crlf = false;
            for (std::size_t i = bom ? 3 : 0; i < raw.size(); ++i)
            {
                if (raw[i] == '\r' && i + 1 < raw.size() && raw[i + 1] == '\n')
                {
                    crlf = true;
                    continue;
                }
                normalized += raw[i];
            }
            if (std::count(normalized.begin(), normalized.end(), '\n') >= 20000)
            {
                error = "Limite de 20000 lignes";
                return false;
            }
            text_ = saved_ = normalized;
            original_      = raw;
            crlf_          = crlf;
            bom_           = bom;
            undo_.clear();
            undoBytes_ = cursor_ = 0;
            index();
            return true;
        }

        void CodeBuffer::clear()
        {
            text_.clear();
            saved_.clear();
            original_.clear();
            undo_.clear();
            cursor_ = undoBytes_ = 0;
            crlf_ = bom_ = false;
            index();
        }

        std::string CodeBuffer::serialize() const
        {
            if (text_ == saved_)
                return original_;
            std::string out = bom_ ? "\xEF\xBB\xBF" : "";
            for (std::size_t i = 0; i < text_.size(); ++i)
            {
                if (crlf_ && text_[i] == '\n')
                    out += '\r';
                out += text_[i];
            }
            return out;
        }

        void CodeBuffer::saved()
        {
            std::string raw = serialize();
            saved_          = text_;
            original_       = raw;
        }

        std::string CodeBuffer::line(std::size_t number) const
        {
            if (number >= lines_.size())
                return "";
            std::size_t end = number + 1 < lines_.size() ? lines_[number + 1] - 1 : text_.size();
            return text_.substr(lines_[number], end - lines_[number]);
        }

        std::size_t CodeBuffer::row() const
        {
            return static_cast<std::size_t>(std::upper_bound(lines_.begin(), lines_.end(), cursor_)
                                            - lines_.begin() - 1);
        }

        std::size_t CodeBuffer::column() const
        {
            std::size_t start = lines_[row()], count = 0;
            while (start < cursor_)
            {
                start = nextChar(text_, start);
                ++count;
            }
            return count;
        }

        void CodeBuffer::place(std::size_t row, std::size_t column)
        {
            if (row >= lines_.size())
                row = lines_.size() - 1;
            std::size_t p   = lines_[row],
                        end = row + 1 < lines_.size() ? lines_[row + 1] - 1 : text_.size();
            while (column-- && p < end)
                p = nextChar(text_, p);
            cursor_ = p;
        }

        bool CodeBuffer::replace(std::size_t start, std::size_t count, const std::string& value)
        {
            std::size_t newSize = text_.size() - count + value.size();
            std::size_t removed = static_cast<std::size_t>(
                std::count(text_.begin() + start, text_.begin() + start + count, '\n'));
            std::size_t added =
                static_cast<std::size_t>(std::count(value.begin(), value.end(), '\n'));
            std::size_t newLines = lines_.size() - 1 - removed + added;
            if (newSize + (crlf_ ? newLines : 0) + (bom_ ? 3 : 0) > 1048576)
                return false;
            if (newLines >= 20000)
                return false;
            undo_.push_back(Snapshot(text_, cursor_));
            undoBytes_ += text_.size();
            while (undo_.size() > 64 || undoBytes_ > 2097152)
            {
                undoBytes_ -= undo_.front().text.size();
                undo_.erase(undo_.begin());
            }
            text_.replace(start, count, value);
            cursor_ = start + value.size();
            index();
            return true;
        }

        bool CodeBuffer::key(uint32_t key)
        {
            std::size_t r = row(), c = column();
            if (key == 0xF800)
                cursor_ = previousChar(text_, cursor_);
            else if (key == 0xF801)
                cursor_ = nextChar(text_, cursor_);
            else if (key == 0xF802)
                place(r ? r - 1 : 0, c);
            else if (key == 0xF803)
                place(std::min(r + 1, lineCount() - 1), c);
            else if (key == 0xF806)
                place(r, 0);
            else if (key == 0xF807)
                place(r, ~std::size_t(0));
            else if (key == 8 && cursor_)
            {
                std::size_t p = previousChar(text_, cursor_);
                return replace(p, cursor_ - p, "");
            }
            else if (key == 127 || key == 0xF805)
            {
                if (cursor_ < text_.size())
                    return replace(cursor_, nextChar(text_, cursor_) - cursor_, "");
            }
            else if (key == 13)
                return replace(cursor_, 0, "\n");
            else if (key == 9)
                return replace(cursor_, 0, "    ");
            else if (key >= 32 && !(key >= 0xF800 && key <= 0xFFFF))
            {
                std::string encoded = utf8(key);
                if (!encoded.empty())
                    return replace(cursor_, 0, encoded);
            }
            return true;
        }

        bool CodeBuffer::undo()
        {
            if (undo_.empty())
                return false;
            text_   = undo_.back().text;
            cursor_ = undo_.back().cursor;
            undoBytes_ -= undo_.back().text.size();
            undo_.pop_back();
            index();
            return true;
        }
    }  // namespace desktop
}  // namespace gaspardos
