#ifndef CORE_STRING_H
#define CORE_STRING_H

#include "math/Math.h"
#include "utils/Check.h"
#include "utils/Utility.h"

namespace Core {
    template<int N>
    class ArrayString final {
        int length;
        u32 hash;
        static_assert(N > 0, "size of array string must be positive");
        u32 data[static_cast<unsigned int>(N)];

    public:
        ArrayString() : length(0), hash(0) {
            data[0] = '\0';
        }

        bool operator==(const char* s) const {
            for(int i = 0; i < length; i++) {
                u32 u = 0;
                if(readUnicode(u, s) != Error::NONE || data[i] != u) {
                    return false;
                }
            }
            return read(s) == 0;
        }

        template<int L>
        bool operator==(const ArrayString<L>& other) const {
            if(length != other.getLength()) {
                return false;
            }
            for(int i = 0; i < length; i++) {
                if(data[i] != other[i]) {
                    return false;
                }
            }
            return true;
        }

        bool operator!=(const char* s) const {
            return !((*this) == s);
        }

        template<int L>
        bool operator!=(const ArrayString<L>& other) const {
            return !((*this) == other);
        }

        u32 operator[](int index) const {
            return data[index];
        }

        int getLength() const {
            return length;
        }

        constexpr int getCapacity() const {
            return N;
        }

        check_return Error append(char c) {
            if(c < 0) {
                return Error::NEGATIVE_ARGUMENT;
            }
            return appendUnicode(static_cast<u32>(c));
        }

        check_return Error append(signed char c) {
            if(c < 0) {
                return Error::NEGATIVE_ARGUMENT;
            }
            return appendUnicode(static_cast<u32>(c));
        }

        check_return Error append(unsigned char c) {
            return appendUnicode(c);
        }

        check_return Error append(const char* s) {
            while(true) {
                u32 u = 0;
                CORE_RETURN_ERROR(readUnicode(u, s));
                if(u == 0) {
                    return Error::NONE;
                }
                CORE_RETURN_ERROR(appendUnicode(u));
            }
        }

        check_return Error append(const signed char* s) {
            return append(reinterpret_cast<const char*>(s));
        }

        check_return Error append(const unsigned char* s) {
            return append(reinterpret_cast<const char*>(s));
        }

        check_return Error append(signed short s) {
            return convertAppend(s);
        }

        check_return Error append(unsigned short s) {
            return convertAppend(s);
        }

        check_return Error append(signed int i) {
            return convertAppend(i);
        }

        check_return Error append(unsigned int i) {
            return convertAppend(i);
        }

        check_return Error append(signed long l) {
            return convertAppend(l);
        }

        check_return Error append(unsigned long l) {
            return convertAppend(l);
        }

        check_return Error append(signed long long ll) {
            return convertAppend(ll);
        }

        check_return Error append(unsigned long long ll) {
            return convertAppend(ll);
        }

        check_return Error append(float f) {
            return convertAppend(static_cast<double>(f));
        }

        check_return Error append(double d) {
            return convertAppend(d);
        }

        check_return Error append(long double ld) {
            return convertAppend(ld);
        }

        check_return Error append(bool b) {
            return b ? append("true") : append("false");
        }

        check_return Error appendUnicode(u32 c) {
            if(length >= N) {
                return Error::CAPACITY_REACHED;
            }
            data[length++] = c;
            addToHash(c);
            return Error::NONE;
        }

        check_return Error append(Error e) {
            return append(getErrorName(e));
        }

        template<typename T>
        check_return Error append(const T& t) {
            return t.toString(*this);
        }

        template<int L>
        check_return Error toString(ArrayString<L>& s) const {
            int l = length; // length changes if &s == this
            for(int i = 0; i < l; i++) {
                CORE_RETURN_ERROR(s.appendUnicode(data[i]));
            }
            return Error::NONE;
        }

        void clear() {
            length = 0;
            hash = 0;
            data[0] = '\0';
        }

        u32 hashCode() const {
            return hash;
        }

        check_return Error print() const {
            for(int i = 0; i < length; i++) {
                u32 c = data[i];
                if(c < (1 << 7)) {
                    CORE_RETURN_ERROR(printChar(c, 0, 0x7F, 0x0));
                } else if(c < (1 << 11)) {
                    CORE_RETURN_ERROR(printChar(c, 6, 0x1F, 0xC0));
                    CORE_RETURN_ERROR(printChar(c, 0, 0x3F, 0x80));
                } else if(c < (1 << 16)) {
                    CORE_RETURN_ERROR(printChar(c, 12, 0x0F, 0xE0));
                    CORE_RETURN_ERROR(printChar(c, 6, 0x3F, 0x80));
                    CORE_RETURN_ERROR(printChar(c, 0, 0x3F, 0x80));
                } else if(c < (1 << 21)) {
                    CORE_RETURN_ERROR(printChar(c, 18, 0x07, 0xF0));
                    CORE_RETURN_ERROR(printChar(c, 12, 0x3F, 0x80));
                    CORE_RETURN_ERROR(printChar(c, 6, 0x3F, 0x80));
                    CORE_RETURN_ERROR(printChar(c, 0, 0x3F, 0x80));
                }
            }
            return Error::NONE;
        }

        check_return Error printLine() const {
            CORE_RETURN_ERROR(print());
            CORE_RETURN_ERROR(Core::putChar('\n'));
            return Error::NONE;
        }

        template<typename... Args>
        check_return Error format(Args&&... args) {
            ArrayString s;
            CORE_RETURN_ERROR(formatBuffer(s, 0, Core::forward<Args>(args)...));
            *this = s;
            return Error::NONE;
        }

        template<int L>
        bool startsWidth(const ArrayString<L>& other, int from = 0) const {
            if(from + other.getLength() > length) {
                return false;
            }
            for(int i = 0; i < other.getLength(); i++) {
                if(data[from + i] != other[i]) {
                    return false;
                }
            }
            return true;
        }

        template<int L>
        int search(const ArrayString<L>& other, int from = 0) const {
            for(int i = from; i < length; i++) {
                if(startsWidth(other, i)) {
                    return i;
                }
            }
            return -1;
        }

        template<int L>
        bool contains(const ArrayString<L>& other, int from = 0) const {
            return search(other, from) >= 0;
        }

        int search(u32 u, int from = 0) const {
            for(int i = from; i < length; i++) {
                if(data[i] == u) {
                    return i;
                }
            }
            return -1;
        }

        bool contains(u32 u, int from = 0) const {
            return search(u, from) >= 0;
        }

        ArrayString substring(int from, int to) const {
            from = Math::max(from, 0);
            to = Math::min(to, length - 1);
            ArrayString<N> s;
            for(int i = from; i <= to; i++) {
                (void)s.appendUnicode(data[i]);
            }
            return s;
        }

        ArrayString substring(int from = 0) const {
            return substring(from, length - 1);
        }

        template<int L1, int L2>
        check_return Error replace(const ArrayString<L1>& search,
                                   const ArrayString<L2>& replace) {
            ArrayString<N> s;
            int i = 0;
            while(i < length) {
                if(startsWidth(search, i)) {
                    CORE_RETURN_ERROR(s.append(replace));
                    i += search.getLength();
                } else {
                    CORE_RETURN_ERROR(s.appendUnicode(data[i]));
                    i++;
                }
            }
            *this = s;
            return Error::NONE;
        }

        void replace(u32 search, u32 replace) {
            hash = 0;
            for(int i = 0; i < length; i++) {
                if(data[i] == search) {
                    data[i] = replace;
                }
                addToHash(data[i]);
            }
        }

    private:
        check_return static Error printChar(u32 u, u32 shift, u32 a, u32 o) {
            return Core::putChar(static_cast<int>(((u >> shift) & a) | o));
        }

        static u32 read(const char*& s) {
            if(*s == '\0') {
                return 0;
            }
            return static_cast<u32>(*(s++));
        }

        static Error readUnicode(u32& u, const char*& s) {
            u = read(s);
            if((u & 0x80) == 0) {
                return Error::NONE;
            }
            if((u & 0xE0) == 0xC0) {
                u32 u2 = read(s);
                if(u2 == 0) {
                    return Error::INVALID_CHAR;
                }
                u = ((u & 0x1F) << 6) | (u2 & 0x3F);
                return Error::NONE;
            } else if((u & 0xF0) == 0xE0) {
                u32 u2 = read(s);
                u32 u3 = read(s);
                if(u2 == 0 || u3 == 0) {
                    return Error::INVALID_CHAR;
                }
                u = ((u & 0xF) << 12) | ((u2 & 0x3F) << 6) | (u3 & 0x3F);
                return Error::NONE;
            } else if((u & 0xF8) == 0xF0) {
                u32 u2 = read(s);
                u32 u3 = read(s);
                u32 u4 = read(s);
                if(u2 == 0 || u3 == 0 || u4 == 0) {
                    return Error::INVALID_CHAR;
                }
                u = ((u & 0x07) << 18) | ((u2 & 0x3F) << 12) |
                    ((u3 & 0x3F) << 6) | (u4 & 0x3F);
                return Error::NONE;
            }
            return Error::INVALID_CHAR;
        }

        void addToHash(u32 u) {
            hash = static_cast<u32>(2120251889) * hash + static_cast<u32>(u);
        }

        template<typename T, typename... Args>
        check_return Error formatBuffer(ArrayString& s, int index, const T& t,
                                        Args&&... args) {
            while(index < length) {
                u32 u = data[index++];
                if(u == '#') {
                    if(index >= length ||
                       (index < length && data[index] != '#')) {
                        break;
                    }
                    index++;
                }
                CORE_RETURN_ERROR(s.appendUnicode(u));
            }
            CORE_RETURN_ERROR(s.append(t));
            return formatBuffer(s, index, Core::forward<Args>(args)...);
        }

        check_return Error formatBuffer(ArrayString& s, int index) {
            while(index < length) {
                CORE_RETURN_ERROR(s.appendUnicode(data[index++]));
            }
            return Error::NONE;
        }

        template<typename T>
        check_return Error convertAppend(T t) {
            char buffer[64];
            CORE_RETURN_ERROR(Core::toString(t, buffer, CORE_SIZE(buffer)));
            return append(static_cast<const char*>(buffer));
        }
    };
}

template<int N>
bool operator==(const char* cs, const Core::ArrayString<N>& s) {
    return s == cs;
}

template<int N>
bool operator!=(const char* cs, const Core::ArrayString<N>& s) {
    return s != cs;
}

#endif