API ViewID AllocViewID(View *view) {
    return {ViewIDs.id++, view};
}

API View *CreateView(BufferID active_buffer) {
    Allocator al           = GetSystemAllocator();
    View     *view         = AllocType(al, View);
    view->id               = AllocViewID(view);
    view->active_buffer    = active_buffer;
    view->carets.allocator = al;
    view->hooks.allocator  = al;
    Add(&view->carets, {0, 0});
    Add(&Views, view);
    return view;
}

void Dealloc(View *view) {
    Dealloc(&view->carets);
    Dealloc(&view->hooks);
    Dealloc(view->carets.allocator, view);
}

API View *FindView(ViewID view_id, View *default_view) {
    For(Views) {
        if (it->id == view_id) {
            return it;
        }
    }
    return default_view;
}

API View *FindView(BufferID buffer_id, View *default_view) {
    For(Views) {
        if (it->active_buffer == buffer_id) {
            return it;
        }
    }
    return default_view;
}

API View *FindView(String name, View *default_view) {
    For(Views) {
        Buffer *buffer = GetBuffer(it->active_buffer);
        if (buffer->name == name) {
            return it;
        }
    }
    return default_view;
}

API View *GetView(ViewID id) {
    return FindView(id, Views[0]);
}

API View *OpenBufferView(String name) {
    Buffer *buffer = BufferOpenFile(name);
    View   *view   = CreateView(buffer->id);
    return view;
}

API bool ViewIsCrumb(ViewID view_id) {
    ForItem(window, Windows) {
        For(window->goto_history) if (it.view_id == view_id) return true;
        For(window->goto_redo) if (it.view_id == view_id) return true;
    }
    return false;
}

bool ViewIsActive(ViewID id) {
    For (Windows) {
        if (it->active_view == id) {
            return true;
        }
    }
    return false;
}

API bool ViewIsReferenced(ViewID view) {
    if (view == NullViewID) {
        return true;
    }

    if (ViewIsCrumb(view)) {
        return true;
    }

    return ViewIsActive(view);
}

void Close(ViewID id) {
    View *view = GetView(id);
    if (view) {
        if (view->id.id == 0) {
            return;
        }
        view->close = true;
        RunGCThisFrame = true;
    }
}

ViewID FindInactiveView(ViewID default_view = NullViewID) {
    For (Views) {
        if (!ViewIsActive(it->id)) return it->id;
    }
    return default_view;
}

String16 FetchLoadWord(View *view) {
    Buffer *buffer = GetBuffer(view->active_buffer);
    Caret caret = view->carets[0];
    Range range = caret.range;
    if (GetSize(caret.range) == 0) range = EncloseLoadWord(buffer, GetFront(caret));
    String16 string = GetString(buffer, range);
    return string;
}

void IdentedNewLine(View *view) {
    Buffer     *buffer = GetBuffer(view->active_buffer);
    Scratch     scratch;
    Array<Edit> edits = BeginEdit(scratch, buffer, view->carets);
    MergeCarets(buffer, &view->carets);
    For(view->carets) {
        Int      front    = GetFront(it);
        Int      line     = PosToLine(buffer, front);
        Int      indent   = GetLineIndent(buffer, line);
        String   string   = Format(scratch, "\n%.*s", (int)indent, "                                                       ");
        String16 string16 = ToString16(scratch, string);
        AddEdit(&edits, it.range, string16);
    }
    EndEdit(buffer, &edits, &view->carets, KILL_SELECTION);
}

Caret FindPrev(Buffer *buffer, String16 needle, Caret caret) {
    Int pos = GetFront(caret);
    String16 medium = GetString(buffer, {0, pos});
    SeekFlag flag = SearchCaseSensitive ? SeekFlag_None : SeekFlag_IgnoreCase;
    if (SearchWordBoundary) {
        flag |= SeekFlag_WordBoundary;
    }

    Caret result = caret;
    Int   index  = 0;
    if (Seek(medium, needle, &index, flag | SeekFlag_MatchFindLast)) {
        result = MakeCaret(index, index + needle.len);
    } else {
        medium = GetString(buffer);
        if (Seek(medium, needle, &index, flag | SeekFlag_MatchFindLast)) {
            result = MakeCaret(index, index + needle.len);
        }
    }

    return result;
}

Caret FindNext(Buffer *buffer, String16 needle, Caret caret) {
    Int pos = GetMax(caret);
    String16 medium = GetString(buffer, {pos, INT64_MAX});
    SeekFlag flag = SearchCaseSensitive ? SeekFlag_None : SeekFlag_IgnoreCase;
    if (SearchWordBoundary) {
        flag |= SeekFlag_WordBoundary;
    }

    Caret result = caret;
    Int   index  = 0;
    if (Seek(medium, needle, &index, flag)) {
        result = MakeCaret(pos + index + needle.len, pos + index);
    } else {
        medium = GetString(buffer);
        if (Seek(medium, needle, &index, flag)) {
            result = MakeCaret(index + needle.len, index);
        }
    }

    return result;
}

Array<Caret> FindAll(Allocator allocator, Buffer *buffer, String16 needle) {
    Array<Caret> result = {allocator};
    String16 string = GetString(buffer);
    String16 start = string;
    SeekFlag flag = SearchCaseSensitive ? SeekFlag_None : SeekFlag_IgnoreCase;
    if (SearchWordBoundary) {
        flag |= SeekFlag_WordBoundary;
    }
    for (;;) {
        Int index = 0;
        if (Seek(string, needle, &index, flag)) {
            Int back = index + (Int)(string.data - start.data);
            Int front = back + needle.len;
            Add(&result, MakeCaret(front, back));
            string = Skip(string, index + needle.len);
        } else {
            break;
        }
    }
    return result;
}

void SelectRange(View *view, Caret caret) {
    view->carets.len = 1;
    view->carets[0]  = caret;
}

void SelectRange(View *view, Range range) {
    SelectRange(view, MakeCaret(range.min, range.max));
}

void SelectEntireBuffer(View *view) {
    Buffer *buffer = GetBuffer(view->active_buffer);
    SelectRange(view, GetRange(buffer));
}

void Find(View *seek_view, String16 needle, bool forward = true) {
    Buffer *seek_buffer = GetBuffer(seek_view->active_buffer);
    Caret   caret       = seek_view->carets[0];
    if (forward) caret = FindNext(seek_buffer, needle, caret);
    if (!forward) caret = FindPrev(seek_buffer, needle, caret);
    SelectRange(seek_view, caret);
    IF_DEBUG(AssertRanges(seek_view->carets));
}

void SelectAll(View *view, String16 needle) {
    Buffer  *buffer        = GetBuffer(view->active_buffer);
    String16 string_buffer = GetString(buffer);

    for (Int pos = 0;;) {
        Int      index  = 0;
        String16 medium = Skip(string_buffer, pos);
        if (!Seek(medium, needle, &index)) {
            break;
        }

        Add(&view->carets, MakeCaret(pos + index + needle.len, pos + index));
        pos += needle.len;
    }
    MergeCarets(buffer, &view->carets);
}

Caret MoveCaret(Buffer *buffer, Caret it, int direction, bool ctrl = false, bool shift = false) {
    Int front      = GetFront(it);
    Int range_size = GetSize(it.range);
    switch (direction) {
    case DIR_UP: {
        if (ctrl && shift) {
            Int pos = GetPrevEmptyLineStart(buffer, front);
            it      = SetFront(it, pos);
        } else if (ctrl) {
            Int pos = GetPrevEmptyLineStart(buffer, it.range.min);
            it      = MakeCaret(pos);
        } else if (shift) {
            if (PosToLine(buffer, front) == 0) {
                it = SetFront(it, 0);
            } else {
                Int pos = OffsetByLine(buffer, front, -1);
                it      = SetFront(it, pos);
            }
        } else {
            if (range_size == 0) {
                Int pos = OffsetByLine(buffer, it.range.min, -1);
                it      = MakeCaret(pos);
            } else {
                it = MakeCaret(it.range.min);
            }
        }
    } break;
    case DIR_DOWN: {
        if (ctrl && shift) {
            Int pos = GetNextEmptyLineStart(buffer, front);
            it      = SetFront(it, pos);
        } else if (ctrl) {
            Int pos = GetNextEmptyLineStart(buffer, it.range.max);
            it      = MakeCaret(pos);
        } else if (shift) {
            if (LastLine(buffer) == PosToLine(buffer, front)) {
                it = SetFront(it, buffer->len);
            } else {
                Int pos = OffsetByLine(buffer, front, 1);
                it      = SetFront(it, pos);
            }
        } else {
            if (range_size == 0) {
                Int pos = OffsetByLine(buffer, it.range.max, 1);
                it      = MakeCaret(pos);
            } else {
                it = MakeCaret(it.range.max);
            }
        }
    } break;
    case DIR_LEFT: {
        if (ctrl && shift) {
            Int pos = GetPrevWordStart(buffer, front);
            it      = SetFront(it, pos);
        } else if (ctrl) {
            if (range_size != 0 && front != it.range.min) {
                it = MakeCaret(it.range.min);
            } else {
                Int pos = GetPrevWordStart(buffer, it.range.min);
                it      = MakeCaret(pos);
            }
        } else if (shift) {
            Int pos = GetPrevChar(buffer, front);
            it      = SetFront(it, pos);
        } else {
            if (range_size == 0) {
                Int pos = GetPrevChar(buffer, it.range.min);
                it      = MakeCaret(pos);
            } else {
                it = MakeCaret(it.range.min);
            }
        }
    } break;
    case DIR_RIGHT: {
        if (ctrl && shift) {
            Int pos = GetNextWordEnd(buffer, front);
            it      = SetFront(it, pos);
        } else if (ctrl) {
            if (range_size != 0 && front != it.range.max) {
                it = MakeCaret(it.range.max);
            } else {
                Int pos = GetNextWordEnd(buffer, it.range.max);
                it      = MakeCaret(pos);
            }
        } else if (shift) {
            Int pos = GetNextChar(buffer, front);
            it      = SetFront(it, pos);
        } else {
            if (range_size == 0) {
                Int pos = GetNextChar(buffer, it.range.max);
                it      = MakeCaret(pos);
            } else {
                it = MakeCaret(it.range.max);
            }
        }
    } break;
    }
    return it;
}

void MoveCarets(View *view, int direction, bool ctrl = false, bool shift = false) {
    Assert(direction < DIR_COUNT);
    Buffer *buffer = GetBuffer(view->active_buffer);
    For(view->carets) {
        it = MoveCaret(buffer, it, direction, ctrl, shift);
    }
}

void MoveCaretsLine(View *view, int direction) {
    Assert(direction == DIR_DOWN || direction == DIR_UP);
    Scratch scratch;

    // @todo: this doesn't work well at the end of buffer
    struct XYPair {
        XY front;
        XY back;
    };

    Buffer     *buffer = GetBuffer(view->active_buffer);
    Array<Edit> edits  = BeginEdit(scratch, buffer, view->carets);
    MergeCarets(buffer, &view->carets);
    Array<XYPair> saved_xy = {scratch};
    For(view->carets) {
        Int eof_current = 0;
        Range lines_to_move_range = {GetFullLineStart(buffer, it.range.min), GetFullLineEnd(buffer, it.range.max, &eof_current)};
        if (lines_to_move_range.min == 0 && direction == DIR_UP) {
            continue;
        }

        Int eof = 0;
        Int next_line_start = lines_to_move_range.max;
        Int next_line_end   = GetFullLineEnd(buffer, next_line_start, &eof);
        Int prev_line_end   = lines_to_move_range.min - 1;
        Int prev_line_start = GetFullLineStart(buffer, prev_line_end);

        if (direction == DIR_DOWN && eof) {
            continue;
        } else if (direction == DIR_UP && eof_current) {
            continue;
        }

        String16 string = Copy16(scratch, GetString(buffer, lines_to_move_range));

        AddEdit(&edits, lines_to_move_range, {});
        if (direction == DIR_DOWN) {
            AddEdit(&edits, MakeRange(next_line_end), string);
        } else {
            AddEdit(&edits, MakeRange(prev_line_start), string);
        }

        Add(&saved_xy, {PosToXY(buffer, GetFront(it)), PosToXY(buffer, GetBack(it))});
    }
    EndEdit(buffer, &edits, &view->carets, !KILL_SELECTION);

    Int line_offset = direction == DIR_UP ? -1 : +1;
    for (Int i = 0; i < saved_xy.len; i += 1) {
        Caret  &caret  = view->carets[i];
        XYPair &xypair = saved_xy[i];
        xypair.front.line += line_offset;
        xypair.back.line += line_offset;
        Int front = XYToPos(buffer, xypair.front);
        Int back  = XYToPos(buffer, xypair.back);

        caret = MakeCaret(front, back);
    }
}

void CreateCursorVertical(View *view, int direction) {
    Assert(direction == DIR_UP || direction == DIR_DOWN);
    Buffer *buffer = GetBuffer(view->active_buffer);

    Int line_offset = direction == DIR_UP ? -1 : 1;

    Scratch      scratch;
    Array<Caret> arr = {scratch};
    For(view->carets) {
        if (PosToLine(buffer, it.range.min) == PosToLine(buffer, it.range.max)) {
            Int f = OffsetByLine(buffer, GetFront(it), line_offset);
            Int b = OffsetByLine(buffer, GetBack(it), line_offset);
            Add(&arr, MakeCaret(f, b));
        } else {
            Int   pos   = direction == DIR_UP ? it.range.min : it.range.max;
            Caret caret = MakeCaret(pos);
            caret       = MoveCaret(buffer, caret, direction);
            Add(&arr, caret);
        }
    }
    For(arr) Add(&view->carets, it);
    MergeCarets(buffer, &view->carets);
}

void Delete(View *view, int direction, bool ctrl = false) {
    Assert(direction == DIR_LEFT || direction == DIR_RIGHT);
    Scratch scratch;

    Buffer     *buffer = GetBuffer(view->active_buffer);
    Array<Edit> edits  = BeginEdit(scratch, buffer, view->carets);

    // Select things to delete
    For(view->carets) {
        if (GetSize(it.range)) continue;
        if (direction == DIR_LEFT) {

            // Delete indent in multiple of IndentSize
            Range indent_range = GetIndentRangeAtPos(buffer, it.range.min);
            if (ctrl == false && it.range.min > indent_range.min && it.range.max <= indent_range.max) {
                Int offset    = it.range.min - indent_range.min;
                Int to_delete = (offset % (ConfigIndentSize));
                if (to_delete == 0) to_delete = ConfigIndentSize;
                to_delete = Clamp(to_delete, (Int)1, ConfigIndentSize);
                for (Int i = 0; i < to_delete; i += 1) {
                    it = MoveCaret(buffer, it, direction, false, SHIFT_PRESS);
                }

            } else {
                it = MoveCaret(buffer, it, direction, ctrl, SHIFT_PRESS);
            }
        } else {
            it = MoveCaret(buffer, it, direction, ctrl, SHIFT_PRESS);
        }
    }

    MergeCarets(buffer, &view->carets);
    For(view->carets) AddEdit(&edits, it.range, {});
    EndEdit(buffer, &edits, &view->carets, true);
}

void EncloseSpace(View *view) {
    Buffer *buffer = GetBuffer(view->active_buffer);
    For (view->carets) {
        it.range.min = GetPrevEmptyLineStart(buffer, it.range.min);
        it.range.max = GetNextEmptyLineStart(buffer, it.range.max);
    }
}

Array<Range> GetSelectedLinesSorted(Allocator allocator, View *view) {
    Scratch      scratch(allocator);
    Buffer      *buffer     = GetBuffer(view->active_buffer);
    Array<Caret> caret_copy = TightCopy(scratch, view->carets);
    Array<Caret> temp       = TightCopy(scratch, view->carets);
    if (view->carets.len > 1) MergeSort(view->carets.len, caret_copy.data, temp.data);

    Array<Range> result = {allocator};
    For(caret_copy) {
        Int   min_line   = PosToLine(buffer, it.range.min);
        Int   max_line   = PosToLine(buffer, it.range.max);
        Range line_range = {min_line, max_line + 1};

        if (result.len == 0) {
            Add(&result, line_range);
            continue;
        }

        Range *last = GetLast(result);
        if (AreOverlapping(*last, line_range)) {
            last->max = Max(last->max, line_range.max);
        } else {
            Add(&result, line_range);
        }
    }
    return result;
}

void IndentSelectedLines(View *view, bool shift = false) {
    Scratch scratch;
    Buffer *buffer = GetBuffer(view->active_buffer);

    Array<Edit> edits = BeginEdit(scratch, buffer, view->carets);
    MergeCarets(buffer, &view->carets);

    Array<Range> line_ranges_to_indent = GetSelectedLinesSorted(scratch, view);
    For(line_ranges_to_indent) {
        for (Int i = it.min; i < it.max; i += 1) {
            Range pos_range_of_line = GetLineRange(buffer, i);

            if (!shift) {
                String16 whitespace_string = {u"                                      ", ConfigIndentSize};
                AddEdit(&edits, {pos_range_of_line.min, pos_range_of_line.min}, whitespace_string);
            } else {
                String16 string         = GetString(buffer, pos_range_of_line);
                Int      whitespace_len = 0;
                for (Int i = 0; i < ConfigIndentSize && i < string.len && string.data[i] == ' '; i += 1) {
                    whitespace_len += 1;
                }

                AddEdit(&edits, {pos_range_of_line.min, pos_range_of_line.min + whitespace_len}, u"");
            }
        }
    }
    EndEdit(buffer, &edits, &view->carets, !KILL_SELECTION);
    view->update_scroll = false;
}

void MoveCursorToSide(View *view, int direction, bool shift = false) {
    Assert(direction == DIR_LEFT || direction == DIR_RIGHT);
    Buffer *buffer = GetBuffer(view->active_buffer);

    For(view->carets) {
        Int pos = GetFront(it);
        if (direction == DIR_RIGHT) {
            pos = GetLineEnd(buffer, pos);
        } else {
            Int indent  = GetIndentAtPos(buffer, pos);
            Int new_pos = GetLineStart(buffer, pos);
            if (new_pos + indent != pos) {
                pos = new_pos + indent;
            } else {
                pos = new_pos;
            }
        }

        if (shift) {
            it = SetFront(it, pos);
        } else {
            it.range.max = it.range.min = pos;
        }
    }
}

Array<Edit> ReplaceEx(Allocator scratch, View *view, String16 string) {
    Buffer     *buffer = GetBuffer(view->active_buffer);
    Array<Edit> edits  = BeginEdit(scratch, buffer, view->carets);
    MergeCarets(buffer, &view->carets);
    For(view->carets) AddEdit(&edits, it.range, string);
    EndEdit(buffer, &edits, &view->carets, KILL_SELECTION);
    return edits;
}

void Replace(View *view, String16 string) {
    Scratch scratch;
    ReplaceEx(scratch, view, string);
}

void DuplicateLine(View *view, int direction) {
    Assert(direction == DIR_UP || direction == DIR_DOWN);
    Scratch scratch;

    Buffer *buffer = GetBuffer(view->active_buffer);
    BeginEdit(scratch, buffer, view->carets);
    MergeCarets(buffer, &view->carets);

    Array<Edit> edits = {scratch};
    For(view->carets) {
        Int eof = 0;
        Range range = {};
        range.max = GetFullLineEnd(buffer, it.range.max, &eof);
        range.min = GetFullLineStart(buffer, it.range.min);
        range.min -= Clamp(eof, (Int)0, buffer->len);
        String16 string = Copy16(scratch, GetString(buffer, range));

        Int pos = direction == DIR_UP ? range.min : range.max;
        AddEdit(&edits, MakeRange(pos), string);
    }
    EndEdit(buffer, &edits, &view->carets, !KILL_SELECTION);

    Int coef = direction == DIR_UP ? -1 : 1;
    for (Int i = 0; i < edits.len; i += 1) {
        Caret *caret = view->carets.data + i;

        XY xymin = PosToXY(buffer, caret->range.min);
        XY xymax = PosToXY(buffer, caret->range.max);
        Int line_count = xymax.line - xymin.line + 1;

        xymin.line += coef * line_count;
        xymax.line += coef * line_count;

        caret->range.min = XYToPos(buffer, xymin);
        caret->range.max = XYToPos(buffer, xymax);
    }
}

void KillSelectedLines(View *view) {
    Scratch scratch;
    Buffer *buffer = GetBuffer(view->active_buffer);
    SaveCaretHistoryBeforeBeginEdit(buffer, view->carets);

    For (view->carets) {
        Int eof = 0;
        it.range.max = GetFullLineEnd(buffer, it.range.max, &eof);
        it.range.min = GetFullLineStart(buffer, it.range.min);
        it.range.min -= Clamp(eof, (Int)0, buffer->len);
    }
    Replace(view, u"");
}

void EncloseLine(View *view) {
    Buffer *buffer = GetBuffer(view->active_buffer);
    For (view->carets) {
        Int eof = 0;
        it.range.max = GetFullLineEnd(buffer, it.range.max, &eof);
        it.range.min = GetFullLineStart(buffer, it.range.min);
    }
}

void EncloseScope(View *view) {
    Buffer *buffer = GetBuffer(view->active_buffer);
    For (view->carets) {
        it.range = EncloseScope(buffer, it.range.min - 1, it.range.max + 1, u'(', u')');
        it.range.min = Clamp(buffer, it.range.min + 1);
        it.range.max = Clamp(buffer, it.range.max - 1);
    }
}
