/*
 * This file is part of OpenTTD.
 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
 */

/** @file textbuf.cpp Textbuffer handling. */

#include "stdafx.h"

#include "textbuf_type.h"
#include "string_func.h"
#include "strings_func.h"
#include "core/utf8.hpp"
#include "gfx_type.h"
#include "gfx_func.h"
#include "gfx_layout.h"
#include "window_func.h"

#include "safeguards.h"

/**
 * Try to retrieve the current clipboard contents.
 *
 * @note OS-specific function.
 * @return The (optional) clipboard contents.
 */
std::optional<std::string> GetClipboardContents();

int _caret_timer;


/**
 * Checks if it is possible to delete a character.
 * @param backspace if set, delete the character before the caret,
 * otherwise, delete the character after it.
 * @return true if a character can be deleted in the given direction.
 */
bool Textbuf::CanDelChar(bool backspace)
{
	return backspace ? this->caretpos != 0 : this->caretpos < this->buf.size();
}

/**
 * Delete a character from a textbuffer, either with 'Delete' or 'Backspace'
 * The character is delete from the position the caret is at
 * @param keycode Type of deletion, either WKC_BACKSPACE or WKC_DELETE
 * @return Return true on successful change of Textbuf, or false otherwise
 */
bool Textbuf::DeleteChar(uint16_t keycode)
{
	bool word = (keycode & WKC_CTRL) != 0;

	keycode &= ~WKC_SPECIAL_KEYS;
	if (keycode != WKC_BACKSPACE && keycode != WKC_DELETE) return false;

	bool backspace = keycode == WKC_BACKSPACE;

	if (!CanDelChar(backspace)) return false;

	size_t start;
	size_t len;
	if (word) {
		/* Delete a complete word. */
		if (backspace) {
			/* Delete whitespace and word in front of the caret. */
			start = this->char_iter->Prev(StringIterator::ITER_WORD);
			len = this->caretpos - start;
		} else {
			/* Delete word and following whitespace following the caret. */
			start = this->caretpos;
			len = this->char_iter->Next(StringIterator::ITER_WORD) - start;
		}
		/* Update character count. */
		this->chars -= static_cast<uint16_t>(Utf8StringLength(std::string_view(this->buf).substr(start, len)));
	} else {
		/* Delete a single character. */
		if (backspace) {
			/* Delete the last code point in front of the caret. */
			Utf8View view(this->buf);
			auto it = view.GetIterAtByte(this->caretpos);
			--it;
			start = it.GetByteOffset();
			len = this->caretpos - start;
			this->chars--;
		} else {
			/* Delete the complete character following the caret. */
			start = this->caretpos;
			len = this->char_iter->Next(StringIterator::ITER_CHARACTER) - start;
			/* Update character count. */
			this->chars -= static_cast<uint16_t>(Utf8StringLength(std::string_view(this->buf).substr(start, len)));
		}
	}

	/* Move the remaining characters over the marker */
	this->buf.erase(start, len);

	if (backspace) this->caretpos -= static_cast<uint16_t>(len);

	this->UpdateStringIter();
	this->UpdateWidth();
	this->UpdateCaretPosition();
	this->UpdateMarkedText();

	return true;
}

/**
 * Delete every character in the textbuffer
 */
void Textbuf::DeleteAll()
{
	this->buf.clear();
	this->chars = 1;
	this->pixels = this->caretpos = this->caretxoffs = 0;
	this->markpos = this->markend = this->markxoffs = this->marklength = 0;
	this->UpdateStringIter();
}

/**
 * Insert a character to a textbuffer. If maxwidth of the Textbuf is zero,
 * we don't care about the visual-length but only about the physical
 * length of the string
 * @param key Character to be inserted
 * @return Return true on successful change of Textbuf, or false otherwise
 */
bool Textbuf::InsertChar(char32_t key)
{
	auto [src, len] = EncodeUtf8(key);
	if (this->buf.size() + len < this->max_bytes && this->chars + 1 <= this->max_chars) {
		/* Make space in the string, then overwrite it with the Utf8 encoded character. */
		this->buf.insert(this->caretpos, src, len);
		this->chars++;
		this->caretpos += len;

		this->UpdateStringIter();
		this->UpdateWidth();
		this->UpdateCaretPosition();
		this->UpdateMarkedText();
		return true;
	}
	return false;
}

/**
 * Insert a string into the text buffer. If maxwidth of the Textbuf is zero,
 * we don't care about the visual-length but only about the physical
 * length of the string.
 * @param str String to insert.
 * @param marked Replace the currently marked text with the new text.
 * @param caret Move the caret to this point in the insertion string.
 * @param insert_location Position at which to insert the string.
 * @param replacement_end Replace all characters from #insert_location up to this location with the new string.
 * @return True on successful change of Textbuf, or false otherwise.
 */
bool Textbuf::InsertString(std::string_view str, bool marked, std::optional<size_t> caret, std::optional<size_t> insert_location, std::optional<size_t> replacement_end)
{
	uint16_t insertpos = (marked && this->marklength != 0) ? this->markpos : this->caretpos;
	if (insert_location.has_value()) {
		insertpos = static_cast<uint16_t>(*insert_location);
		if (insertpos >= this->buf.size()) return false;

		if (replacement_end.has_value()) {
			this->DeleteText(insertpos, static_cast<uint16_t>(*replacement_end), str.empty());
		}
	} else {
		if (marked) this->DiscardMarkedText(str.empty());
	}

	if (str.empty()) return false;

	uint16_t chars = 0;
	uint16_t bytes;
	{
		Utf8View view(str);
		auto cur = view.begin();
		const auto end = view.end();
		while (cur != end) {
			if (!IsValidChar(*cur, this->afilter)) break;

			auto next = cur;
			++next;
			if (this->buf.size() + next.GetByteOffset() >= this->max_bytes) break;
			if (this->chars + chars + 1 > this->max_chars) break;

			cur = next;
			chars++;
		}
		bytes = static_cast<uint16_t>(cur.GetByteOffset());
	}
	if (bytes == 0) return false;

	/* Move caret if needed. */
	if (caret.has_value()) this->caretpos = insertpos + static_cast<uint16_t>(*caret);

	if (marked) {
		this->markpos = insertpos;
		this->markend = insertpos + bytes;
	}

	this->buf.insert(insertpos, str.substr(0, bytes));

	this->chars += chars;
	if (!marked && !caret.has_value()) this->caretpos += bytes;
	assert(this->buf.size() < this->max_bytes);
	assert(this->chars <= this->max_chars);

	this->UpdateStringIter();
	this->UpdateWidth();
	this->UpdateCaretPosition();
	this->UpdateMarkedText();

	return true;
}

/**
 * Insert a chunk of text from the clipboard onto the textbuffer. Get TEXT clipboard
 * and append this up to the maximum length (either absolute or screenlength). If maxlength
 * is zero, we don't care about the screenlength but only about the physical length of the string
 * @return true on successful change of Textbuf, or false otherwise
 */
bool Textbuf::InsertClipboard()
{
	auto contents = GetClipboardContents();
	if (!contents.has_value()) return false;

	return this->InsertString(contents.value(), false);
}

/**
 * Delete a part of the text.
 * @param from Start of the text to delete.
 * @param to End of the text to delete.
 * @param update Set to true if the internal state should be updated.
 */
void Textbuf::DeleteText(uint16_t from, uint16_t to, bool update)
{
	assert(from <= to);

	/* Strip marked characters from buffer. */
	this->chars -= static_cast<uint16_t>(Utf8StringLength(std::string_view(this->buf).substr(from, to - from)));
	this->buf.erase(from, to - from);

	auto fixup = [&](uint16_t &pos) {
		if (pos <= from) return;
		if (pos <= to) {
			pos = from;
		} else {
			pos -= to - from;
		}
	};

	/* Fixup caret if needed. */
	fixup(this->caretpos);

	/* Fixup marked text if needed. */
	fixup(this->markpos);
	fixup(this->markend);

	if (update) {
		this->UpdateStringIter();
		this->UpdateCaretPosition();
		this->UpdateMarkedText();
	}
}

/**
 * Discard any marked text.
 * @param update Set to true if the internal state should be updated.
 */
void Textbuf::DiscardMarkedText(bool update)
{
	if (this->markend == 0) return;

	this->DeleteText(this->markpos, this->markend, update);
	this->markpos = this->markend = this->markxoffs = this->marklength = 0;
}

/**
 * Get the current text.
 * @return Current text.
 */
std::string_view Textbuf::GetText() const
{
	return this->buf;
}

/** Update the character iter after the text has changed. */
void Textbuf::UpdateStringIter()
{
	this->char_iter->SetString(this->buf);
	size_t pos = this->char_iter->SetCurPosition(this->caretpos);
	this->caretpos = pos == StringIterator::END ? 0 : (uint16_t)pos;
}

/** Update pixel width of the text. */
void Textbuf::UpdateWidth()
{
	this->pixels = GetStringBoundingBox(this->buf, FS_NORMAL).width;
}

/** Update pixel position of the caret. */
void Textbuf::UpdateCaretPosition()
{
	const auto pos = GetCharPosInString(this->buf, this->caretpos, FS_NORMAL);
	this->caretxoffs = _current_text_dir == TD_LTR ? pos.left : pos.right;
}

/** Update pixel positions of the marked text area. */
void Textbuf::UpdateMarkedText()
{
	if (this->markend != 0) {
		const auto pos = GetCharPosInString(this->buf, this->markpos, FS_NORMAL);
		const auto end = GetCharPosInString(this->buf, this->markend, FS_NORMAL);
		this->markxoffs = std::min(pos.left, end.left);
		this->marklength = std::max(pos.right, end.right) - this->markxoffs;
	} else {
		this->markxoffs = this->marklength = 0;
	}
}

/**
 * Move to previous character position.
 * @param what Move ITER_CHARACTER or ITER_WORD.
 * @return true iff able to move.
 */
bool Textbuf::MovePrev(StringIterator::IterType what)
{
	if (this->caretpos == 0) return false;

	size_t pos = this->char_iter->Prev(what);
	if (pos == StringIterator::END) return true;

	this->caretpos = static_cast<uint16_t>(pos);
	this->UpdateCaretPosition();
	return true;
}

/**
 * Move to next character position.
 * @param what Move ITER_CHARACTER or ITER_WORD.
 * @return true iff able to move.
 */
bool Textbuf::MoveNext(StringIterator::IterType what)
{
	if (this->caretpos >= this->buf.size()) return false;

	size_t pos = this->char_iter->Next(what);
	if (pos == StringIterator::END) return true;

	this->caretpos = static_cast<uint16_t>(pos);
	this->UpdateCaretPosition();
	return true;
}

/**
 * Handle text navigation with arrow keys left/right.
 * This defines where the caret will blink and the next character interaction will occur
 * @param keycode Direction in which navigation occurs (WKC_CTRL |) WKC_LEFT, (WKC_CTRL |) WKC_RIGHT, WKC_END, WKC_HOME
 * @return Return true on successful change of Textbuf, or false otherwise
 */
bool Textbuf::MovePos(uint16_t keycode)
{
	switch (keycode) {
		case WKC_LEFT:
		case WKC_CTRL | WKC_LEFT: {
			auto move_type = (keycode & WKC_CTRL) != 0 ? StringIterator::ITER_WORD : StringIterator::ITER_CHARACTER;
			return (_current_text_dir == TD_LTR) ? this->MovePrev(move_type) : this->MoveNext(move_type);
		}

		case WKC_RIGHT:
		case WKC_CTRL | WKC_RIGHT: {
			auto move_type = (keycode & WKC_CTRL) != 0 ? StringIterator::ITER_WORD : StringIterator::ITER_CHARACTER;
			return (_current_text_dir == TD_LTR) ? this->MoveNext(move_type) : this->MovePrev(move_type);
		}

		case WKC_HOME:
			this->caretpos = 0;
			this->char_iter->SetCurPosition(this->caretpos);
			this->UpdateCaretPosition();
			return true;

		case WKC_END:
			this->caretpos = static_cast<uint16_t>(this->buf.size());
			this->char_iter->SetCurPosition(this->caretpos);
			this->UpdateCaretPosition();
			return true;

		default:
			break;
	}

	return false;
}

/**
 * Initialize the textbuffer by supplying it the buffer to write into
 * and the maximum length of this buffer
 * @param max_bytes maximum size in bytes, including terminating '\0'
 * @param max_chars maximum size in chars, including terminating '\0'
 */
Textbuf::Textbuf(uint16_t max_bytes, uint16_t max_chars)
	: char_iter(StringIterator::Create())
{
	assert(max_bytes != 0);
	assert(max_chars != 0);

	this->afilter    = CS_ALPHANUMERAL;
	this->max_bytes  = max_bytes;
	this->max_chars  = max_chars == UINT16_MAX ? max_bytes : max_chars;
	this->caret      = true;
	this->DeleteAll();
}

/**
 * Copy a string into the textbuffer.
 * @param text Source.
 */
void Textbuf::Assign(std::string_view text)
{
	size_t bytes = std::min<size_t>(this->max_bytes - 1, text.size());
	this->buf = StrMakeValid(text.substr(0, bytes));

	/* Make sure the name isn't too long for the text buffer in the number of
	 * characters (not bytes). max_chars also counts the '\0' characters. */
	Utf8View view(text);
	auto it = view.begin();
	const auto end = view.end();
	for (size_t len = 1; len < this->max_chars && it != end; ++len) ++it;

	if (it != end) {
		this->buf.erase(it.GetByteOffset(), std::string::npos);
	}

	this->UpdateSize();
}


/**
 * Update Textbuf type with its actual physical character and screenlength
 * Get the count of characters in the string as well as the width in pixels.
 * Useful when copying in a larger amount of text at once
 */
void Textbuf::UpdateSize()
{
	this->chars = static_cast<uint16_t>(Utf8StringLength(this->buf) + 1); // terminating zero
	assert(this->buf.size() < this->max_bytes);
	assert(this->chars <= this->max_chars);

	this->caretpos = static_cast<uint16_t>(this->buf.size());
	this->UpdateStringIter();
	this->UpdateWidth();
	this->UpdateMarkedText();

	this->UpdateCaretPosition();
}

/**
 * Handle the flashing of the caret.
 * @return True if the caret state changes.
 */
bool Textbuf::HandleCaret()
{
	/* caret changed? */
	bool b = !!(_caret_timer & 0x20);

	if (b != this->caret) {
		this->caret = b;
		return true;
	}
	return false;
}

HandleKeyPressResult Textbuf::HandleKeyPress(char32_t key, uint16_t keycode)
{
	bool edited = false;

	switch (keycode) {
		case WKC_ESC: return HKPR_CANCEL;

		case WKC_RETURN: case WKC_NUM_ENTER: return HKPR_CONFIRM;

		case (WKC_CTRL | 'V'):
		case (WKC_SHIFT | WKC_INSERT):
			edited = this->InsertClipboard();
			break;

		case (WKC_CTRL | 'U'):
			this->DeleteAll();
			edited = true;
			break;

		case WKC_BACKSPACE: case WKC_DELETE:
		case WKC_CTRL | WKC_BACKSPACE: case WKC_CTRL | WKC_DELETE:
			edited = this->DeleteChar(keycode);
			break;

		case WKC_LEFT: case WKC_RIGHT: case WKC_END: case WKC_HOME:
		case WKC_CTRL | WKC_LEFT: case WKC_CTRL | WKC_RIGHT:
			this->MovePos(keycode);
			break;

		default:
			if (IsValidChar(key, this->afilter)) {
				edited = this->InsertChar(key);
			} else {
				return HKPR_NOT_HANDLED;
			}
			break;
	}

	return edited ? HKPR_EDITING : HKPR_CURSOR;
}
