/********************************************************
 *  ██████╗  ██████╗████████╗██╗
 * ██╔════╝ ██╔════╝╚══██╔══╝██║
 * ██║  ███╗██║        ██║   ██║
 * ██║   ██║██║        ██║   ██║
 * ╚██████╔╝╚██████╗   ██║   ███████╗
 *  ╚═════╝  ╚═════╝   ╚═╝   ╚══════╝
 * Geophysical Computational Tools & Library (GCTL)
 *
 * Copyright (c) 2023  Yi Zhang (yizhang-geo@zju.edu.cn)
 *
 * GCTL is distributed under a dual licensing scheme. You can redistribute 
 * it and/or modify it under the terms of the GNU Lesser General Public 
 * License as published by the Free Software Foundation, either version 2 
 * of the License, or (at your option) any later version. You should have 
 * received a copy of the GNU Lesser General Public License along with this 
 * program. If not, see <http://www.gnu.org/licenses/>.
 * 
 * If the terms and conditions of the LGPL v.2. would prevent you from using 
 * the GCTL, please consider the option to obtain a commercial license for a 
 * fee. These licenses are offered by the GCTL's original author. As a rule, 
 * licenses are provided "as-is", unlimited in time for a one time fee. Please 
 * send corresponding requests to: yizhang-geo@zju.edu.cn. Please do not forget 
 * to include some description of your company and the realm of its activities. 
 * Also add information on how to contact you by electronic and paper mail.
 ******************************************************/

#if defined _WINDOWS || __WIN32__
#include <io.h>
// Test for file existence
#define F_OK 0
#endif

#include "term_io.h"

//在终端显示一个简易的GCTL图标
void gctl::display_logo(std::ostream &sout)
{
	sout << "   ___   ___  _____   __\n";
	sout << "  / _ \\ / __\\/__   \\ / /\n";
	sout << " / /_\\// /     / /\\// /\n";
	sout << "/ /_\\\\/ /___  / /  / /___\n";
	sout << "\\____/\\____/  \\/   \\____/\n";
	sout << "Geophysical Computational Tools & Library\n";
	sout << "Author: Dr. Yi Zhang (yizhang-geo@zju.edu.cn)\n\n";
	return;
}

int gctl::terminal_width()
{
	int width;
	//获取终端窗口的行列数
#ifdef _WINDOWS
	CONSOLE_SCREEN_BUFFER_INFO csbi;
	GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
	width = csbi.srWindow.Right - csbi.srWindow.Left + 1;
#else
	struct winsize w;
	ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
	width = w.ws_col;
#endif

	return width;
}

int gctl::terminal_height()
{
	int height;
	//获取终端窗口的行列数
#ifdef _WINDOWS
	CONSOLE_SCREEN_BUFFER_INFO csbi;
	GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
	height = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
#else
	struct winsize w;
	ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
	height = w.ws_row;
#endif

	return height;
}

gctl::cli_viewer::cli_viewer()
{
    // 初始化ncurses
    initscr();
    cbreak(); // 禁用行缓冲
    noecho(); // 不显示输入字符
    keypad(stdscr, TRUE); // 启用键盘扩展键
    timeout(0); // 设置非阻塞输入
    curs_set(0); // 隐藏光标
}

// 析构函数
gctl::cli_viewer::~cli_viewer()
{
    // 清理ncurses
    endwin();
}

// 设置显示内容
void gctl::cli_viewer::setData(const std::vector<std::string>& data)
{
    lines = data;
    return;
}

void gctl::cli_viewer::addData(const std::string& l)
{
    lines.push_back(l);
    return;
}

// 显示文件内容并进入查看循环
void gctl::cli_viewer::display()
{
    int maxLines = LINES - 1; // 终端的行数（减去提示行）
    int startLine = 0; // 当前显示的起始行
    int startX = 0; // 当前水平滚动的起始位置
    int maxLineLength = 0; // 最长行的长度

    // 计算最长行的长度
    for (const auto& line : lines)
    {
        maxLineLength = std::max(maxLineLength, static_cast<int>(line.length()));
    }

    // 主循环
    while (true)
    {
        werase(stdscr); // 清屏但不闪烁

        // 显示文件内容
        for (int i = startLine; i < startLine + maxLines && i < lines.size(); ++i)
        {
            const std::string& line = lines[i];
            if (startX < line.length())
            {
                mvprintw(i - startLine, 0, "%s", line.substr(startX).c_str());
            }
        }

        // 在最后一行显示提示信息
        mvprintw(LINES - 1, 0, "Use arrow keys or mouse wheel to scroll. Press Q or ESC to exit.");

        int ch = getch(); // 获取按键
        if (ch == KEY_UP)
        {
            startLine = std::max(0, startLine - 1); // 向上滚动
        }
        else if (ch == KEY_DOWN)
        {
            startLine = std::min(startLine + 1, static_cast<int>(lines.size()) - maxLines); // 向下滚动
        }
        else if (ch == KEY_LEFT)
        {
            startX = std::max(0, startX - 1); // 向左滚动
        }
        else if (ch == KEY_RIGHT)
        {
            startX = std::min(startX + 1, maxLineLength - COLS); // 向右滚动
        } 
        else if (ch == 'q' || ch == 'Q' || ch == 27)
        { // 按Q或ESC退出
            break;
        }
        wrefresh(stdscr); // 刷新屏幕
    }
    return;
}