/********************************************************
 *  ██████╗  ██████╗████████╗██╗
 * ██╔════╝ ██╔════╝╚══██╔══╝██║
 * ██║  ███╗██║        ██║   ██║
 * ██║   ██║██║        ██║   ██║
 * ╚██████╔╝╚██████╗   ██║   ███████╗
 *  ╚═════╝  ╚═════╝   ╚═╝   ╚══════╝
 * 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_TRI_CONE_H
#define _GCTL_TRI_CONE_H

#include "vertex.h"
#include "entity.h"

namespace gctl
{
    // Declaration of the basic edge type
    template <typename A> struct type_tricone;
    // edge type of attribute type of void
    typedef type_tricone<void> tri_cone;

    static int cone_order[12] = {0,1,2,0,3,1,1,3,2,2,3,0};

	/**
	 * @brief      三棱锥（一种特别的四面体，第四个顶点必须为坐标原点，不记录 在使用时赋值即可）。
	 * 主要用于球坐标下的重力数据正反演计算
	 * 
	 * @note 注意三棱锥顶面的顶点排序为逆时针（从外部观察）。在初始化中会自动对顶点进行排序。第四个顶点
	 * 是原点位置
     * 
     * z
     * |       2
     * |      //\
     * |    /  /  \
     * |  /    /     \
     * 0--------------1
     * |     /      /
     * |     /     /
     * |    /     /
     * |    /    /
     * |   /    /
     * |   /   /
     * |  /   /
     * |  /  /
     * | /  /
     * | / /
     * |/ /
     * |//
     * O(3)---------------------->x
	 */
    template <typename A>
	struct type_tricone : public entity<vertex3dc, 4, A>
	{
        /**
         * Constructor
         */
		type_tricone();
        /**
         * @brief      De-constructor
         */
        virtual ~type_tricone(){}
        /**
         * @brief      Set object from parameters
         *
         * @warning    This function will locate memories to store vertice
         *
         * @param[in]  p0     The first point
         * @param[in]  p1     The second point
         * @param[in]  p2     The third point
         * @param[in]  p3     The origin point
         * @param[in]  index  The element index
         */
        type_tricone(const point3ds &ps0, const point3ds &ps1, const point3ds &ps2, const point3dc &ori, int index = 0);
        /**
         * @brief      Constructor with initial parameters
         *
         * @param      vert0    The vertex 0
         * @param      vert1    The vertex 1
         * @param      vert2    The vertex 2
         * @param[in]  index    The index
         */
		type_tricone(vertex3dc &vert0, vertex3dc &vert1, vertex3dc &vert2, int index = 0);
        /**
         * @brief      Set object from parameters
         *
         * @warning    This function will locate memories to store vertice
         *
         * @param[in]  p0     The first point
         * @param[in]  p1     The second point
         * @param[in]  p2     The third point
         * @param[in]  p3     The origin point
         * @param[in]  index  The element index
         */
        void set(const point3ds &ps0, const point3ds &ps1, const point3ds &ps2, const point3dc &ori, int index = 0);
        /**
         * @brief      Set object parameters
         *
         * @param      vert0    The vertex 0
         * @param      vert1    The vertex 1
         * @param      vert2    The vertex 2
         * @param      ori_ptr  The origin pointer
         * @param[in]  index    The index
         */
		void set(vertex3dc &vert0, vertex3dc &vert1, vertex3dc &vert2, int index = 0);
        /**
         * @brief      Sets the origin.
         *
         * @param      ori_ptr  The origin pointer
         */
		void set_origin(vertex3dc &ori);
        /**
         * @brief      Get pointer of the j-th vertex on the i-th facet
         *
         * @param[in]  i     facet index (smaller than 4)
         * @param[in]  j     vertex index (smaller than 3)
         *
         * @return     vertex pointer
         */
        vertex3dc *get(unsigned int i, unsigned int j) const;
        /**
         * @brief      Get pointer of the j-th vertex on the i-th facet. Without any checks
         *
         * @param[in]  i     facet index (smaller than 4)
         * @param[in]  j     vertex index (smaller than 3)
         *
         * @return     { description_of_the_return_value }
         */
        vertex3dc *fget(unsigned int i, unsigned int j) const;
	};

    template <typename A>
    type_tricone<A>::type_tricone() : entity<vertex3dc, 4, A>::entity(){}

    template <typename A>
    type_tricone<A>::type_tricone(const point3ds &ps0, const point3ds &ps1, const point3ds &ps2, 
        const point3dc &ori, int index) : type_tricone()
    {
        set(ps0, ps1, ps2, ori, index);
    }

    template <typename A>
    type_tricone<A>::type_tricone(vertex3dc &vert0, vertex3dc &vert1, 
        vertex3dc &vert2, int index) : type_tricone()
    {
        set(vert0, vert1, vert2, index);
    }

    template <typename A>
    void type_tricone<A>::set(const point3ds &ps0, const point3ds &ps1, const point3ds &ps2, 
        const point3dc &ori, int index)
    {
        if (index < 0)
        {
            throw out_of_range("Invalid index number, From type_tricone::set(...)");
        }

        for (int i = 0; i < 4; ++i)
        {
            this->vert[i] = new vertex3dc;
        }
        this->self_host = true;

        point3dc p0 = s2c(ps0);
        point3dc p1 = s2c(ps1);
        point3dc p2 = s2c(ps2);

        // 重新检查顶点的排序 初始化为逆时针排序
        point3dc tmp_p;
        if (dot(p0 - ori, cross(p1 - p0, p2 - p0)) < 0)
        {
            tmp_p = p1; p1 = p2; p2 = tmp_p;
        }

        this->id = index;
        this->vert[0]->set(p0, 4*index + 0);
        this->vert[1]->set(p1, 4*index + 1);
        this->vert[2]->set(p2, 4*index + 2);
        this->vert[3]->set(ori, 4*index + 3);
        return;
    }

    template <typename A>
    void type_tricone<A>::set(vertex3dc &vert0, vertex3dc &vert1, vertex3dc &vert2, int index)
    {
        if (index < 0)
        {
            throw out_of_range("Invalid index number, From type_tricone::set(...)");
        }

        this->id = index;
        this->vert[0] = &vert0;
        this->vert[1] = &vert1; 
        this->vert[2] = &vert2;

        if (this->vert[3] != nullptr)
        {
            // 检查顶点的排序 初始化为逆时针排序
            vertex3dc *tmp_ptr;
            if (dot(*this->vert[0] - *this->vert[3], cross(*this->vert[1] - *this->vert[0], 
                *this->vert[2] - *this->vert[0])) < 0)
            {
                tmp_ptr = this->vert[1];
                this->vert[1] = this->vert[2];
                this->vert[2] = tmp_ptr;
            }
        }
        return;
    }

    template <typename A>
    void type_tricone<A>::set_origin(vertex3dc &ori)
    {
        this->vert[3] = &ori;

        if (this->vert[0] != nullptr && this->vert[1] != nullptr && this->vert[2] != nullptr)
        {
            // 重新检查顶点的排序 初始化为逆时针排序
            vertex3dc *tmp_ptr;
            if (dot(*this->vert[0] - *this->vert[3], cross(*this->vert[1] - *this->vert[0], 
                *this->vert[2] - *this->vert[0])) < 0)
            {
                tmp_ptr = this->vert[1];
                this->vert[1] = this->vert[2];
                this->vert[2] = tmp_ptr;
            }
        }
        return;
    }

    template <typename A>
    vertex3dc *type_tricone<A>::get(unsigned int i, unsigned int j) const
    {
        if (i > 3 || j > 2)
        {
            throw out_of_range("Invalid facet or vertex index. From type_tricone::get(...)");
        }

        if (this->vert[0] == nullptr || this->vert[1] == nullptr || 
            this->vert[2] == nullptr || this->vert[3] == nullptr)
        {
            throw domain_error("Invalid pointer. From type_tricone::get(...)");
        }

        return this->vert[cone_order[3*i+j]];
    }

    template <typename A>
    vertex3dc *type_tricone<A>::fget(unsigned int i, unsigned int j) const
    {
        return this->vert[cone_order[3*i+j]];
    }
}

#endif // _GCTL_TRI_CONE_H