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

void gctl::triangle2d_mesh::init(std::string in_name, std::string in_info, const array<vertex2dc> &in_nodes_, 
	const array<triangle2d> &in_triangles)
{
	check_initiated(true); // 检查是否已经初始化
	base_mesh::init(TRI_TET_MESH, MESH_2D, in_name, in_info);

	node_num_ = in_nodes_.size();
	ele_num_  = in_triangles.size();

	nodes_.resize(node_num_);
	for (int i = 0; i < node_num_; i++)
	{
		nodes_[i] = in_nodes_[i];
	}

	elems_.resize(ele_num_);
	for (int i = 0; i < ele_num_; i++)
	{
		elems_[i].id = i;
		for (int j = 0; j < 3; j++)
		{
			elems_[i].vert[j] = nodes_.get(in_triangles[i].vert[j]->id);
		}
	}

	initialized_ = true;
	return;
}

void gctl::triangle2d_mesh::show_mesh_dimension(std::ostream &os) const
{
	os << "Node num: " << node_num_ << std::endl;
	os << "Elem num: " << ele_num_ << std::endl;
	return;
}

void gctl::triangle2d_mesh::load_binary(std::string filename)
{
	check_initiated(true); // 检查是否已经初始化

	std::ifstream infile;
	gctl::open_infile(infile, filename, ".2m", std::ios::in|std::ios::binary);

	// 读入网格头信息
	load_headinfo(infile, TRI_TET_MESH, MESH_2D);

	// 读入网格信息
	infile.read((char*)&node_num_, sizeof(int));
	infile.read((char*)&ele_num_, sizeof(int));

	nodes_.resize(node_num_);
	elems_.resize(ele_num_);

	for (int i = 0; i < node_num_; i++)
	{
		infile.read((char*)nodes_.get(i), sizeof(gctl::vertex2dc));
	}

	int in_index;
	for (int i = 0; i < ele_num_; i++)
	{
		elems_[i].id = i;
		for (int j = 0; j < 3; j++)
		{
			infile.read((char*)&in_index, sizeof(int));
			elems_[i].vert[j] = nodes_.get(in_index);
		}
	}

	// 读入模型数据单元
	load_datablock(infile);

	infile.close();
	initialized_ = true;
	return;
}

void gctl::triangle2d_mesh::save_binary(std::string filename)
{
	check_initiated(); // 检查是否已经初始化

	std::ofstream outfile;
	gctl::open_outfile(outfile, filename, ".2m", std::ios::out|std::ios::binary);

	// 首先输出网格的头信息
	save_headinfo(outfile);

	// 输出网格信息
	outfile.write((char*)&node_num_, sizeof(int));
	outfile.write((char*)&ele_num_, sizeof(int));

	for (int i = 0; i < node_num_; i++)
	{
		outfile.write((char*)nodes_.get(i), sizeof(gctl::vertex2dc));
	}

	int in_index;
	for (int i = 0; i < ele_num_; i++)
	{
		for (int j = 0; j < 3; j++)
		{
			in_index = elems_[i].vert[j]->id;
			outfile.write((char*)&in_index, sizeof(int));
		}
	}

	// 输出的模型数据单元
	save_datablock(outfile);

	outfile.close();
	return;
}

gctl::triangle2d_mesh::triangle2d_mesh() : base_mesh::base_mesh(){}

gctl::triangle2d_mesh::triangle2d_mesh(std::string in_name, std::string in_info, const array<vertex2dc> &in_nodes_, 
	const array<triangle2d> &in_triangles)
{
	init(in_name, in_info, in_nodes_, in_triangles);
}

gctl::triangle2d_mesh::~triangle2d_mesh(){}

const gctl::array<gctl::vertex2dc> &gctl::triangle2d_mesh::get_nodes() const
{
	check_initiated(); // 检查是否已经初始化
	return nodes_;
}

const gctl::array<gctl::triangle2d> &gctl::triangle2d_mesh::get_elements() const
{
	check_initiated(); // 检查是否已经初始化
	return elems_;
}

void gctl::triangle2d_mesh::reorder2anticlockwise()
{
	check_initiated(); // 检查是否已经初始化
	vertex2dc *v_ptr;
    for (size_t i = 0; i < get_elenum(); i++)
    {
        if (cross(*elems_[i].vert[1] - *elems_[i].vert[0], *elems_[i].vert[2] - *elems_[i].vert[0]) < 0)
        {
            v_ptr = elems_[i].vert[1]; 
            elems_[i].vert[1] = elems_[i].vert[2];
            elems_[i].vert[2] = v_ptr;
        }
    }
    return;
}

void gctl::triangle2d_mesh::load_triangle(std::string filename, index_packed_e packed)
{
	gctl::read_Triangle_node(filename, nodes_, packed);
	gctl::read_Triangle_element(filename, elems_, nodes_, packed);

	// 设置名称与信息等
	node_num_ = nodes_.size();
	ele_num_  = elems_.size();
	base_mesh::init(TRI_TET_MESH, MESH_2D, filename, "Imported from a .node and .ele file.");
	initialized_ = true;
	return;
}

void gctl::triangle2d_mesh::load_gmsh(std::string filename, index_packed_e packed)
{
	meshio_.init_file(filename, Input);
	meshio_.set_packed(packed, Input);
	meshio_.read_mesh(elems_, nodes_, &elems_tag_);

	// 设置名称与信息等
	node_num_ = nodes_.size();
	ele_num_  = elems_.size();
	base_mesh::init(TRI_TET_MESH, MESH_2D, filename, "Imported from a .msh file.");
	initialized_ = true;
	return;
}

void gctl::triangle2d_mesh::load_gmsh_groups()
{
	check_initiated(); // 检查是否已经初始化
	meshio_.read_physical_groups(groups_);
	return;
}

void gctl::triangle2d_mesh::save_gmsh(std::string filename, index_packed_e packed)
{
	meshio_.init_file(filename, Output);
	meshio_.set_packed(packed, Output);
	meshio_.save_mesh(elems_, nodes_);
	return;
}

void gctl::triangle2d_mesh::groups2data(std::string datname, _1s_vector phynames, _1d_vector phyvals)
{
	check_initiated(); // 检查是否已经初始化

	if (phynames.size() != phyvals.size() || phynames.empty())
	{
		throw std::invalid_argument("The size of phynames and phyvals must be the same and non-empty.");
	}

	if (groups_.empty() || elems_tag_.empty())
	{
		throw std::invalid_argument("No physical groups found.");
	}

	if (elems_tag_.empty()) throw std::invalid_argument("No physical tags found.");
	for (size_t i = 0; i < ele_num_; i++)
	{
		if (elems_tag_[i].empty()) throw std::invalid_argument("No physical tags found.");
	}

	array<int> tag_idx(phynames.size());
	for (size_t i = 0; i < phynames.size(); i++)
	{
		tag_idx[i] = meshio_.physical_name2tag(groups_, phynames[i]);
	}

	if (saved(datname))
	{
		meshdata &dat = get_data(datname);
		if (dat.loctype_ != ElemData) throw std::invalid_argument("The data type must be ElemData.");

		for (size_t i = 0; i < ele_num_; i++)
		{
			for (size_t e = 0; e < phynames.size(); e++)
			{
				if (elems_tag_[i][0] == tag_idx[e])
				{
					dat.datval_[i] = phyvals[e];
					break;
				}
			}
		}
	}
	else
	{
		meshdata &newdat = add_data(ElemData, Scalar, datname, 0.0);
		
		for (size_t i = 0; i < ele_num_; i++)
		{
			for (size_t e = 0; e < phynames.size(); e++)
			{
				if (elems_tag_[i][0] == tag_idx[e])
				{
					newdat.datval_[i] = phyvals[e];
					break;
				}
			}
		}
	}
	return;
}