/********************************************************
 *  ██████╗  ██████╗████████╗██╗
 * ██╔════╝ ██╔════╝╚══██╔══╝██║
 * ██║  ███╗██║        ██║   ██║
 * ██║   ██║██║        ██║   ██║
 * ╚██████╔╝╚██████╗   ██║   ███████╗
 *  ╚═════╝  ╚═════╝   ╚═╝   ╚══════╝
 * 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.
 ******************************************************/

#ifndef _GCTL_GETOPT_HELP_H
#define _GCTL_GETOPT_HELP_H

#ifdef _WINDOWS
#include <windows.h>
#include "getopt_win.h"
#else
#include <sys/ioctl.h>
#include "getopt.h"
#endif

#include "../core/str.h"
#include "../io/term_io.h"

namespace gctl
{
	struct option_info
	{
		/**
		 * The following three variables we added here are mainly used to generate the
		 * 'help' page. The variable 'info' represents a short message that explains what
		 * the option does. 'format' express the argument's format that the option takes.
		 * Additionally, The variable 'manda' indicates whether the option is mandatory 
		 * or optional.
		 */
		const char *info;
		const char *format;
		bool manda;
	};

	/**
	 * @brief      display formatted help information in terminal
	 * 
	 * This function will display formated help information in the terminal using
	 * the standard error output. We choose the error output to avoid unexpected
	 * redirection and make sure the information will appear in the terminal.
	 *
	 * @param[in]  proname       The program's name.
	 * @param[in]  brief         The brief information show right after the program's name.
	 * @param[in]  exp_longopts  The pointer of expanded longopts
	 * @param      stdout   标准输出信道
	 */
	void getopt_long_help(const option *longopts, const option_info *expd_longopts, const char* proname, 
		const char* brief, std::ostream& sout=std::clog, std::string extra_usage = "");

	/**
	 * @brief      Display the help information of one option indicated by its id.
	 *
	 * @param[in]  val   The option's value
	 * @param      exp_longopts  The expanded longopts
	 * @param      stdout   标准输出信道
	 */
	void getopt_long_option_info(int val, const option *longopts, const option_info *expd_longopts, std::ostream& sout=std::clog);

	/**
	 * @brief      命令行参数拾取与帮助信息显示
	 * 
	 * 此类基于GNU getopt_long()函数 更多信息可查阅相关资料
	 * 
	 * 选项参数拾取规则（命令参数规则的说明）
	 * 1. 每个选项都包含一个短选项（一个字符）和一个长选项（一个字符串）。选项的名称必需唯一
	 * 2. has_arg = no_argument 表示选项不接受参数
	 * 3. has_arg = required_argument 表示选项后必需跟参数 可紧贴短选项或者空一格 长选项必需空一格或者用=号连接（推荐空格）
	 * 4. has_arg = optional_argument 表示选项后可跟参数 也可不跟 有参数时如果是短选项必需紧贴 长选项必需用=号连接
	 */
	class flags_parser
	{
	public:
		flags_parser();
		virtual ~flags_parser();

		/**
		 * @brief      添加选项信息
		 *
		 * @param[in]  s_name   选项的短名称 一般为一个大写或小写字母
		 * @param[in]  f_name   选项的长名称
		 * @param[in]  has_arg  选项是否接收参数
		 * @param      flag     设置get_arg()函数的返回值，如果此参数不为NULL则get_arg()会在成功识别到参数时将s_name的值拷贝给flag指向的变量，同时返回0。
		 * @param[in]  info     选项的简介信息
		 * @param[in]  format   选项的参数格式
		 * @param[in]  manda    选项是否为必须的，表示每次运行程序时都必须设置的参数。
		 */
		void add_opt(int s_name, const char* f_name, int has_arg, int *flag, const char* info, 
			const char* format, bool manda);

		/**
		 * @brief      配置命令行参数选项
		 * 
		 * 在调用参数拾取与帮助信息显示函数前需要初始化
		 *
		 * @param[in]  argc  命令行参数的个数
		 * @param      argv  命令行参数的指针
		 */
		void configure(int argc, char **argv);

		/**
		 * @brief      检测是否所有必需元素都拾取成功
		 *
		 * @return     是否通过
		 */
		bool pass_mandatory();

		/**
		 * @brief      检查命令行选项中是否有待检查的选项
		 *
		 * @param[in]  s_name  待检查的选项
		 *
		 * @return     有则返回1，无返回0，强制选项无返回-1
		 */
		int set_opt(const int s_name);

		/**
		 * @brief      检查命令行选项中是否有待检查的选项
		 *
		 * @param[in]  f_name  待检查的选项长名称
		 *
		 * @return     有则返回1，无返回0，强制选项无返回-1
		 */
		int set_opt(const char* f_name);

		/**
		 * @brief      检查命令行选项中是否有待检查的选项并返回参数值
		 *
		 * @param[in]  s_name  待检查的选项
		 *
		 * @return     成功则返回参数值，否则返回NULL，对于可选参数选项，如果选项后无参数则返回NO_ARG
		 */
		std::string get_arg(const int s_name);

		/**
		 * @brief      检查命令行选项中是否有待检查的选项并返回参数值
		 *
		 * @param[in]  s_name  待检查的选项长名称
		 *
		 * @return     成功则返回参数值，否则返回NULL，对于可选参数选项，如果选项后无参数则返回NO_ARG
		 */
		std::string get_arg(const char* f_name);

		/**
		 * @brief      拾取命令行参数
		 *
		 * @param[in]  tar_val  目标选项的短名称列表
		 * @param[in]  ret_str  目标选项的参数值
		 */
		void get_argv(std::initializer_list<char> tar_val, std::initializer_list<std::string*> ret_str);

		/**
		 * @brief      打印帮助信息页面
		 */
		void show_help_page(std::ostream& sout = std::clog, std::string extra_usage = "");

		/**
		 * @brief      显示对应选项的帮助信息
		 *
		 * @param[in]  s_name  选项名称
		 */
		void show_option_info(int s_name, std::ostream& sout=std::clog);

		/**
		 * @brief      显示对应选项的帮助信息
		 *
		 * @param[in]  s_name  选项名称
		 */
		void show_option_info(const char* f_name, std::ostream& sout=std::clog);

		/**
		 * @brief      设置程序名称
		 *
		 * @param[in]  proname  程序名称
		 */
		void set_proname(const char* proname);

		/**
		 * @brief      设置程序简介信息
		 *
		 * @param[in]  proinfo  简介信息
		 */
		void set_proinfo(const char* proinfo);

		/**
		 * @brief      设置未找到选项时的返回字符串，默认为NULL
		 *
		 * @param[in]  in_str  输入字符串
		 */
		void set_nofound_return(std::string in_str);

		/**
		 * @brief      设置可选参数选项的默认返回字符串，默认为NO_ARG
		 *
		 * @param[in]  in_str  输入字符串
		 */
		void set_noarg_return(std::string in_str);

		/**
		 * @brief      显示选项识别字符串
		 *
		 * @param      stdout   标准输出信道
		 */
		void show_arg_format(std::ostream& sout=std::clog);

	protected:
		std::vector<option> rec_opts_;
		std::vector<option_info> rec_info_;
		std::string arg_format_;
		std::string pro_name_;
		std::string pro_info_;
		std::string nofound_return_;
		std::string noarg_return_;

		int argc_;
		char **argv_;
		bool configured_;
		bool failed_mandatory_;
	};
}

#endif //_GCTL_GETOPT_HELP_H