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

#include "file_io.h"

//测试打开输入文件 如果成功则返回0并输出信息 否则返回1
void gctl::open_infile(std::ifstream &infile, std::string filename, std::string extension, 
	std::ios_base::openmode mode)
{
	if (filename == "")
	{
		throw std::domain_error("Empty file name. From open_infile(...)");
	}

	// 文件流开启则先关闭文件
	if (infile.is_open()) infile.close();
	// 检查文件后缀名是否与所给后缀一致 若无制定后缀名则跳过
	if (extension != "")
	{
		int exlen = extension.length();
		int filen = filename.length();
		// 文件名无后缀或者后缀名与制定类型不一致
		if (exlen >= filen || filename.substr(filen-exlen, filen) != extension)
		{
			// 1以指定后缀名打开文件
			infile.open(filename+extension, mode);
			if (!infile)
			{
				throw gctl::domain_error("Fail to open file: " + filename + extension + ". From open_infile(...)");
			}
			return;
		}
	}

	// 无指定后缀名或者文件名包含后缀名 直接打开文件
	infile.open(filename, mode);
	if (!infile)
	{
		throw gctl::domain_error("Fail to open file: " + filename + ". From open_infile(...)");
	}
	return;
}

void gctl::open_matched_infile(std::ifstream &infile, std::string filename, 
	std::string exten_pattern, std::ios_base::openmode mode)
{
	if (exten_pattern == "" || filename == "")
	{
		throw std::domain_error("Empty file name or extension(s). From open_matched_infile(...)");
	}

	if (infile.is_open()) infile.close();

	std::vector<std::string> extens;
	parse_string_to_vector(exten_pattern, ',', extens);

	int exlen, filen = filename.length();
	for (int i = 0; i < extens.size(); ++i)
	{
		exlen = extens[i].length();
		if (filename.substr(filen-exlen, filen) == extens[i])
		{
			infile.open(filename, mode);
			if (!infile)
			{
				throw domain_error("Fail to open file: " + filename + ". From open_matched_infile(...)");
			}
			return;
		}
	}

	// 没有找到包含允许的后缀名的文件 开始依次添加后缀名并尝试打开文件
	for (int i = 0; i < extens.size(); ++i)
	{
		if (access((filename+extens[i]).c_str(), F_OK) != -1)
		{
			infile.open(filename+extens[i], mode);
			if (!infile)
			{
				throw domain_error("Fail to open file: " + filename + extens[i] + ". From open_matched_infile(...)");
			}
			return;
		}
	}

	throw domain_error("Fail to open file: " + filename + ". Desired file extension: " + exten_pattern + ". From open_matched_infile(...)");
	return;
}

//测试打开输出文件 如果成功则返回0并输出信息 否则返回1
void gctl::open_outfile(std::ofstream &outfile, std::string filename, std::string extension, 
	std::ios_base::openmode mode)
{
	if (filename == "")
	{
		throw domain_error("Empty file name. From open_outfile(...)");
	}

	// 文件流开启则先关闭文件
	if (outfile.is_open()) outfile.close();
	// 检查文件后缀名是否与所给后缀一致 若无制定后缀名则跳过
	if (extension != "")
	{
		int exlen = extension.length();
		int filen = filename.length();
		// 文件名无后缀或者后缀名与制定类型不一致
		if (exlen >= filen || filename.substr(filen-exlen, filen) != extension)
		{
			// 1以指定后缀名打开文件
			outfile.open(filename+extension, mode);
			if (!outfile)
			{
				throw domain_error("Fail to create file: " + filename + extension + ". From open_outfile(...)");
			}
			return;
		}
	}

	// 无指定后缀名或者文件名包含后缀名 直接打开文件
	outfile.open(filename, mode);
	if (!outfile)
	{
		throw domain_error("Fail to create file: " + filename + ". From open_outfile(...)");
	}
	return;
}

void gctl::open_matched_outfile(std::ofstream &outfile, std::string filename, 
	std::string exten_pattern, std::ios_base::openmode mode)
{
	if (exten_pattern == "" || filename == "")
	{
		throw domain_error("Empty file name or extension(s). From open_matched_outfile(...)");
	}

	if (outfile.is_open()) outfile.close();

	std::vector<std::string> extens;
	parse_string_to_vector(exten_pattern, ',', extens);

	int exlen, filen = filename.length();
	for (int i = 0; i < extens.size(); ++i)
	{
		exlen = extens[i].length();
		if (filename.substr(filen-exlen, filen) == extens[i])
		{
			outfile.open(filename, mode);
			if (!outfile)
			{
				throw domain_error("Fail to create file: " + filename + ". From open_matched_outfile(...)");
			}
			return;
		}
	}

	// 没有找到包含允许的后缀名的文件 开始依次添加后缀名并尝试打开文件
	for (int i = 0; i < extens.size(); ++i)
	{
		if (access((filename+extens[i]).c_str(), F_OK) != -1)
		{
			outfile.open(filename+extens[i], mode);
			if (!outfile)
			{
				throw domain_error("Fail to create file: " + filename + extens[i] + ". From open_matched_outfile(...)");
			}
			return;
		}
	}

	throw domain_error("Fail to create file: " + filename + ". Desired file extension: " + exten_pattern + ". From open_matched_outfile(...)");
	return;
}

void gctl::parse_filename(std::string filename, std::string &naked_name, std::string &exten_name)
{
	naked_name = filename.substr(0, filename.rfind("."));
	exten_name = filename.substr(filename.find_last_of('.'));
	return;
}