<?php
    /**
     * Base unit entity file.
     *
     * Creates the entity and makes it available.
     *
     * @category Entity
     */

    /**
     * Require dependent entities if not present.
     */
    require_once(PATH::ENTITY . "Entity.php");
    require_once(PATH::ENTITY . "K_Skill.php");
    require_once(PATH::ENTITY . "K_Leader_Skill.php");
    require_once(PATH::ENTITY . "K_Source.php");
    require_once(PATH::ENTITY . "K_Unit_Transformation.php");

    /**
     * A unit.
     *
     * Represents an object from the table 'k_unit'.
     *
     * @category Entity
     */
    class K_Unit extends Entity{

        /**
         * @var int Unit identifier.
         */
        public $id;

        /**
         * @var int Unit family id.
         */
        public $family;

        /**
         * @var string Unit name.
         */
        public $name;

        /**
         * @var int Unit element id.
         */
        public $element;

        /**
         * @var string Element name (title case)
         */
        public $element_name;

        /**
         * @var int Unit archetype id.
         */
        public $archetype;

        /**
         * @var string Archetype name (title case).
         */
        public $archetype_name;

        /**
         * @var int Default star level.
         */
        public $base_stars;

        /**
         *@var int  Default star level.
         */
        public $natural_stars;

        /**
         * @var bool Indicates if the unit is obtainable.
         */
        public $obtainable;

        /**
         * @var bool Indicates if the unit can be awakened.
         */
        public $can_awaken;

        /**
         * @var string Bonus when awakening.
         */
        public $awaken_bonus;

        /**
         * @var int Required skill-ups.
         */
        public $skill_ups_to_max;

        /**
         * @var K_Leader_Skill Unit's leader skill.
         */
        public $leader_skill;

        /**
         * @var int Base HP.
         */
        public $hp;

        /**
         * @var int Base attack.
         */
        public $atk;

        /**
         * @var int Base defense.
         */
        public $defense;

        /**
         * @var int Speed.
         */
        public $speed;

        /**
         * @var int Critical rate.
         */
        public $crit_rate;

        /**
         * @var int Critical damage.
         */
        public $crit_damage;

        /**
         * @var int Resistance
         */
        public $resistance;

        /**
         * @var int Accuracy.
         */
        public $accuracy;

        /**
         * @var int Raw HP.
         */
        public $raw_hp;

        /**
         * @var int Raw attack.
         */
        public $raw_atk;

        /**
         * @var int Raw Defense.
         */
        public $raw_defense;

        /**
         * @var int HP at max_level.
         */
        public $max_lvl_hp;

        /**
         * @var int Attack at max_level.
         */
        public $max_lvl_atk;

        /**
         * @var int Defense at max_level.
         */
        public $max_lvl_defense;

        /**
         * @var K_Unit Unit it awakens from.
         */
        public $awakens_from;

        /**
         * @var K_Unit Unit it awakens to.
         */
        public $awakens_to;

        /**
         * @var bool Indicates if the unit is a fusion ingredient.
         */
        public $fusion_food;

        /**
         * @var bool Indicates if the unit is homunculus.
         */
        public $homunculus;

        /**
         * @var int The crafting cost (homunculus only).
         */
        public $craft_cost;

        /**
         * @var \K_Unit_Skill[] Unit skills.
         */
        public $skill = [];

        /**
         * @var mixed[] Required essences to awaken the unit.
         *
         * Formed by arrays of:
         * [
         *   "element" => "",
         *   "grade" => "",
         *   "amount" => 
         * ]
         */
        public $essences = [];

        /**
         * @var int \K_Source[] Sources the unit can be get from.
         */
        public $sources = [];

        /**
         * @var string Unit title.
         * If awakened, it will be the awakened from name.
         * If unawakened, it will be <element> <name>.
         */
        public $title;

        /**
         * @var K_Unit_Transformation The transformation the unit can undergo.
         */
        public $transformation;

        /**
         * Constructor.
         *
         * Searches the database and retrieves the information about the
         * unit, populating it and it's items.
         *
         * @param resouce $db Connection to the database.
         * @param int $id Unit identifier.
         * @param bool $complete If false, query only k_unit.
         */
        public function __construct($db, $id, $complete = true){
            parent::__construct($db);
            $s =
              "SELECT " .
              "  id, " .
              "  family, " .
              "  name, " .
              "  element, " .
              "  archetype, " .
              "  base_stars, " .
              "  natural_stars, " .
              "  obtainable, " .
              "  can_awaken, " .
              "  awaken_bonus, " .
              "  skill_ups_to_max, " .
              "  leader_skill, " .
              "  hp, " .
              "  attack, " .
              "  defense, " .
              "  speed, " .
              "  crit_rate, " .
              "  crit_damage, " .
              "  resistance, " .
              "  accuracy, " .
              "  raw_hp, " .
              "  raw_attack, " .
              "  raw_defense, " .
              "  max_lvl_hp, " .
              "  max_lvl_attack, " .
              "  max_lvl_defense, " .
              "  awakens_from, " .
              "  awakens_to, " .
              "  fusion_food, " .
              "  homunculus, " .
              "  craft_cost " .
              "FROM k_unit " .
              "WHERE id = $id; ";
            $q = $this->db->query($s);
            $r = $q->fetchArray(SQLITE3_ASSOC);
            if ($r){
                $this->id = $r["id"];
                $this->family = $r["family"];
                $this->name = HTML::e($r["name"]);
                $this->element = $r["element"];
                switch($this->element){
                    case ELEMENT_ID::WATER:
                        $this->element_name = "Water";
                        break;
                    case ELEMENT_ID::FIRE:
                        $this->element_name = "Fire";
                        break;
                    case ELEMENT_ID::WIND:
                        $this->element_name = "Wind";
                        break;
                    case ELEMENT_ID::LIGHT:
                        $this->element_name = "Light";
                        break;
                    case ELEMENT_ID::DARK:
                        $this->element_name = "Dark";
                        break;
                }
                $this->archetype = $r["archetype"];
                switch($this->archetype){
                    case ARCHETYPE_ID::ATTACK:
                        $this->archetype_name = "Attack";
                        break;
                    case ARCHETYPE_ID::DEFENSE:
                        $this->archetype_name = "Defense";
                        break;
                    case ARCHETYPE_ID::HP:
                        $this->archetype_name = "HP";
                        break;
                    case ARCHETYPE_ID::SUPPORT:
                        $this->archetype_name = "Support";
                        break;
                    case ARCHETYPE_ID::MATERIAL:
                        $this->archetype_name = "Material";
                        break;
                }
                $this->base_stars = $r["base_stars"];
                $this->natural_stars = $r["natural_stars"];
                $this->obtainable = $r["obtainable"];
                $this->can_awaken = $r["can_awaken"];
                $this->awaken_bonus = HTML::e($r["awaken_bonus"]);
                $this->skill_ups_to_max = $r["skill_ups_to_max"];
                if (strlen($r["leader_skill"]) > 0){
                    $this->leader_skill = new K_Leader_Skill($this->db, $r["leader_skill"]);
                }
                $this->hp = $r["hp"];
                $this->attack = $r["attack"];
                $this->defense = $r["defense"];
                $this->speed = $r["speed"];
                $this->crit_rate = $r["crit_rate"];
                $this->crit_damage = $r["crit_damage"];
                $this->resistance = $r["resistance"];
                $this->accuracy = $r["accuracy"];
                $this->raw_hp = $r["raw_hp"];
                $this->raw_attack = $r["raw_attack"];
                $this->raw_defense = $r["raw_defense"];
                $this->max_lvl_hp = $r["max_lvl_hp"];
                $this->max_lvl_attack = $r["max_lvl_attack"];
                $this->max_lvl_defense = $r["max_lvl_defense"];
                $this->awakens_from = $r["awakens_from"];
                $this->awakens_to = $r["awakens_to"];
                $this->fusion_food = $r["fusion_food"];
                $this->homunculus = $r["homunculus"];
                $this->craft_cost = $r["craft_cost"];
            }
            if ($complete){
                $this->load_essences();
                $this->load_skills();
                $this->load_sources();
                $this->load_transformation();
            }
            // No to, no from. Silver unit.
            if ($this->awakens_from == "" && $this->awakens_to == ""){
                $this->title = $this->element_name . " " . $this->name;
            }
            // Awakened
            elseif ($this->awakens_from != ""){
                $this->title = $this->name;
            }
            // Gold
            elseif (strlen($this->awakens_to) > 0){
                $this->title = $this->element_name . " " . $this->name;
            }
        }

        /**
         * Loads the information about the essences to awake the unit. 
         *
         * It is autoatically called at construction time if the
         * $complete parameter is true (by default). No point in calling it
         * twice.
         */
        public function load_essences(){
            $this->essences = [];
            $s =
              "SELECT " .
              "  element, " .
              "  grade, " .
              "  amount " .
              "FROM k_unit_essence " .
              "WHERE " .
              "  unit = " . $this->id . " " .
              "ORDER BY " .
              "  element <> 'Magic', " .
              "  grade <> 'Low', " .
              "  grade <> 'Mid'; ";
            $q = $this->db->query($s);
            while ($r = $q->fetchArray(SQLITE3_ASSOC)){
                $e = [
                    "element" => $r["element"],
                    "grade" => $r["grade"],
                    "amount" => $r["amount"]
                ];
                array_push($this->essences, $e);
            }
        }

        /**
         * Loads the unit transformation.
         *
         * It is automatically called at construction time if the
         * $complete parameter is true (by default). No point in calling it
         * twice.
         */
        public function load_transformation(){
            $this->transformation = null;
            $s = "
              SELECT id
              FROM k_unit_transformation
              WHERE  unit = " . $this->id . ";";
            $q = $this->db->query($s);
            $r = $q->fetchArray(SQLITE3_ASSOC);
            if ($r){
                $this->transformation = new K_Unit_Transformation($this->db, $r["id"]);
            }
        }

        /**
         * Loads the information about the unit skills.
         *
         * It is autoatically called at construction time if the
         * $complete parameter is true (by default). No point in calling it
         * twice.
         */
        public function load_skills(){
            $this->skill = [];
            $s = "
              SELECT skill
              FROM
                k_skill,
                k_unit_skill
              WHERE
                id = skill AND
                unit = " . $this->id . "
              ORDER BY slot;
            ";
            $q = $this->db->query($s);
            while ($r = $q->fetchArray(SQLITE3_ASSOC)){
                array_push($this->skill, new K_Skill($this->db, $r["skill"]));
            }
        }

        /**
         * Loads the information about the unit sources.
         *
         * It is autoatically called at construction time if the
         * $complete parameter is true (by default). No point in calling it
         * twice.
         */
        public function load_sources(){
            $this->sources = [];
            $s =
              "SELECT source " .
              "FROM k_unit_source " .
              "WHERE unit = " . $this->id . ";";
            $q = $this->db->query($s);
            while ($r = $q->fetchArray(SQLITE3_ASSOC)){
                array_push($this->sources, new K_Source($this->db, $r["source"]));
            }
        }

        /**
         * Gets the path to the unit image. The image must be in the
         * img/unit/ directory, and it's name must be the unit id,
         * padded with '0' to 8 digits, and the extension must be '.png'.
         *
         * @return string Image URL, or a fixed unknown image.
         */
        public function get_image(){
            if (file_exists(PATH::BASE . "img/unit/" . str_pad($this->id, 8, '0', STR_PAD_LEFT) . ".png")){
                return URL::IMG["UNIT"] . str_pad($this->id, 8, '0', STR_PAD_LEFT) . ".png";
            }
            else{
                return URL::IMG["UNKNOWN"];
            }
        }

    }
?>

