<?php
include_once("Class/surface.php");
/***************************************************************************
 *                            class.asteroide.php
 *                           ---------------------
 *   begin                : Jeudi 25 décembre 2008
 *   update               : Dimanche 4 janvier 2008
 *   email                : nemunaire@gmail.com
 *
 *
 ***************************************************************************/
class Asteroide extends Surface
{
    public $fondateur;
    public $sante;
    public $nom_alliance;
    public $tag;
    public $wing;
    public $nom_asteroide;
    public $image_asteroide;
    public $position = 5;
    public $cap = 123456789;
    public $credits_alliance;
    public $points_alliance;
    public $url_chat;
    public $url_forum;
    public $details = array();

    /**
     * Constructeur
     * @param    int	$id	id de la planète à importer
     *
     * @return   void
     * @access   public
     */
    public function __construct($id = 0)
    {
        if (!empty($id)) {
            global $table_alliances, $SESS;
            global $alli_batimentsVAR, $spatialVAR;
            $bdd = new BDD();

            //On traite le cas où l'on envoie les coordonnées
            if (is_numeric($id)) {
                $plan = $bdd->unique_query("SELECT * FROM $table_alliances WHERE id = $id;");
                $bdd->deconnexion();
            } elseif (preg_match('#^\[?([0-9]{1,2}):([0-9]{1,2}):?[Aa]?\]?$#', $id, $position)) {
                $plan = $bdd->unique_query("SELECT * FROM $table_alliances WHERE galaxie = ".$position[1]." AND ss = ".$position[2].";");
                $bdd->deconnexion();
            } else {
                die('Erreur #04 : Format de recherche d\'asteroide incorrect !');
            }

            if (!empty($plan)) {
                $this->id = $plan["id"];
                parent::User($SESS->values['id']); //On utilise le numéro d'utilisateur enregistré en session
                $this->galaxie = $plan["galaxie"];
                $this->ss = $plan["ss"];
                $this->points_alliance = @$plan["points_alliance"];
                $this->nom_asteroide = $plan["nom_asteroide"];
                $this->image = $this->image_asteroide = $plan["image_asteroide"];
                $this->debris_met = $plan["debris_met"];
                $this->debris_cri = $plan["debris_cri"];
                $this->metal = $plan["metal"];
                $this->cristal = $plan["cristal"];
                $this->hydrogene = $plan["hydrogene"];
                $this->credits_alliance = $plan["credits_alliance"];
                $this->fondateur = $plan["fondateur"];
                $this->nom_alliance = $plan["nom_alliance"];
                $this->wing = $plan["wing"];
                $this->tag = $plan["tag"];
                $this->url_forum = $plan["url_forum"];
                $this->url_chat = $plan["url_chat"];

                foreach ($alli_batimentsVAR as $bat) {
                    $this->batiments[] = $plan[$bat];
                }
                if (!empty($plan["file_bat"])) {
                    $this->file_bat = unserialize($plan["file_bat"]);
                } else {
                    $this->file_bat = new FileAlliancesBatiments();
                }

                foreach ($spatialVAR as $vais) {
                    $this->vaisseaux[] = $plan[$vais];
                }
                if (!empty($plan["file_vais"])) {
                    $this->file_vais = unserialize($plan["file_vais"]);
                } else {
                    $this->file_vais =  new FileSpatial('vaisseaux');
                }
            }
        }
    }

    public function loadDetails()
    {
        global $table_alliances, $table_user;
        $bdd = new bdd();
        $this->details = array_merge($bdd->unique_query("SELECT presentation, message_inscription, texte_interne, port_chat, chan_chat, image, etat_inscription, defcon, defcon_txt FROM $table_alliances WHERE id = ".$this->id.";"), $bdd->unique_query("SELECT COUNT(id) AS nb_membres FROM $table_user WHERE id_alliance = ".$this->id.";"));
        $bdd->deconnexion();
    }

    public function actualiser($actuFile = true, $first = false)
    {
        //Actualisation des files d'attentes
        if ($actuFile) {
            $this->file_bat->ready($this);
            $this->file_vais->ready($this);
        }
    }

    public function checkAndRetireRessources($metal, $cristal, $hydrogene, $credits)
    {
        if ($this->metal >= $metal && $this->cristal >= $cristal && $this->hydrogene >= $hydrogene && $this->credits_alliance >= $credits) {
            $this->metal -= $metal;
            $this->cristal -= $cristal;
            $this->hydrogene -= $hydrogene;
            $this->credits -= $credits;

            $this->addModif("force");
            $this->addModif("credits_alliance");

            return true;
        } else {
            return false;
        }
    }

    public function addRessources($metal, $cristal, $hydrogene, $credits)
    {
        $perte = 0;

        $this->metal += $metal;
        if ($this->metal > $this->cap) {
            $perte += $this->metal - $this->cap;
            $this->metal = $this->cap;
        }

        $this->cristal += $cristal;
        if ($this->cristal > $this->cap) {
            $perte += $this->cristal - $this->cap;
            $this->cristal = $this->cap;
        }

        $this->hydrogene += $hydrogene;
        if ($this->hydrogene > $this->cap) {
            $perte += $this->hydrogene - $this->cap;
            $this->hydrogene = $this->cap;
        }

        $this->hydrogecredits_alliancene += $credits;

        $this->addModif("force");
        $this->addModif("credits_alliance");

        return $perte;
    }

    public function addCreditsAlliance($credits)
    {
        $this->credits_alliance += $credits;
        $this->addModif("credits_alliance");

        return 0;
    }

    public function addPoints($metal, $cristal, $hydrogene, $credits = 0, $demolition = false)
    {
        global $table_bourse_ressources;
        //On charge les 3 valeurs boursières
        $bdd = new BDD();
        $bourse = $bdd->query("SELECT dispo FROM $table_bourse_ressources;");
        $bdd->deconnexion();

        if (!empty($credits)) {
            //TODO Equivalence non prouvée entre $credits/bourse_calcPrixBase($bourse[0]["dispo"], 0.7); et $credits/bourse_calcPrixBase($bourse[0]["dispo"], 1) * 0.7; dans le but de ne donner que 70% des points
            $metal += $credits/bourse_calcPrixBase($bourse[0]["dispo"], 0.7);
            $cristal += $credits/bourse_calcPrixBase($bourse[1]["dispo"], 0.7);
            $hydrogene += $credits/bourse_calcPrixBase($bourse[2]["dispo"], 0.7);
        }

        $points = bourse_calcPrixBase($bourse[0]["dispo"], $metal);
        $points += bourse_calcPrixBase($bourse[1]["dispo"], $cristal);
        $points += bourse_calcPrixBase($bourse[2]["dispo"], $hydrogene);

        if ($demolition) {
            $this->points_alliance -= intval($points);
        } else {
            $this->points_alliance += intval($points);
        }

        $this->addModif("points_alliance");
    }

    public function creer($fondateur, $mere = false)
    {
        global $VAR, $table_alliances_creation;

        $bdd = new BDD();
        $alliance = $bdd->unique_query("SELECT * FROM $table_alliances_creation WHERE fondateur = ".$fondateur->id_user." LIMIT 1;");
        $bdd->deconnexion();

        //On vérifie que l'alliance n'a pas déjà été créée
        if (empty($alliance)) {
            return 1;
        }

        //Définition des paramètres de l'utilisateur pour l'astéroide
        $this->fondateur = $alliance["fondateur"];
        $this->race = $fondateur->race;

        //Génération du nombre de case et de l'image en fonction de la position dans le système
        $this->sante = 1;
        $this->nom_alliance = $alliance["nom_alliance"];
        $this->tag = $alliance["tag"];
        $this->nom_asteroide = $alliance["nom_alliance"];
        $this->image_asteroide = mt_rand(1, 3);

        $this->modif = array("fondateur", "race", "nom_alliance", "galaxie", "ss", "tag", "nom_asteroide", "image_asteroide");
    }

    /**
     * Destructeur
     *
     * @return   void
     * @access   public
     */
    public function __destruct()
    {
        if (empty($this->ss) || empty($this->fondateur)) {
            return;
        }
        if (DEBUG) {
            var_dump($this);
        }

        global $table_alliances;
        if (empty($this->id)) {
            $outNomChamps = array();
            $outValeurs = array();
            $bdd = new BDD();
            foreach ($this->modif as $modif) {
                //On gère les champs variables tableaux
                if (is_array($modif)) {
                    if ($modif[0] == "batiments") {
                        $calc = dDonnees::nameVAR("alli_batiments");
                    } else {
                        $calc = dDonnees::nameVAR($modif[0]);
                    }

                    if (!isset(${$calc.'VAR'})) {
                        global ${$calc.'VAR'};
                    }

                    $outNomChamps[] = ${$calc.'VAR'}[$modif[1]];
                    $outValeurs[] = $this->{$modif[0]}[$modif[1]];
                } elseif ($modif == "force") {
                    $outNomChamps[] = "metal";
                    $outNomChamps[] = "cristal";
                    $outNomChamps[] = "hydrogene";

                    $outValeurs[] = $this->metal;
                    $outValeurs[] = $this->cristal;
                    $outValeurs[] = $this->hydrogene;
                } elseif (!is_array($this->{$modif})) {
                    $bdd->escape($this->{$modif});
                    $outNomChamps[] = $modif;
                    if (is_int($this->{$modif}) || is_float($this->{$modif})) {
                        $outValeurs[] = $this->{$modif};
                    } else {
                        $outValeurs[] = "'".$this->{$modif}."'";
                    }
                } else {
                    if (is_array($this->{$modif}) && $modif != "coeff_bat" && $modif != "vaisseaux" && $modif != "terrestres" && $modif != "casernes" && $modif != "technologies" && $modif != "batiments") {
                        $prep = serialize($this->{$modif});
                        $bdd->escape($prep);
                        $outNomChamps[] = $modif;
                        $outValeurs[] = "'$prep'";
                    } else {
                        $calc = dDonnees::nameVAR($modif);

                        if (!isset(${$calc.'VAR'})) {
                            global ${$calc.'VAR'};
                        }

                        foreach ($this->{$modif} as $j => $value) {
                            $outNomChamps[] = ${$calc.'VAR'}[$j];
                            $outValeurs[] = $value;
                        }
                    }
                }
            }
            //On supprime le lien de construction de l'alliance
            $bdd->query("DELETE FROM $table_alliances_creation WHERE fondateur = ".$this->fondateur.";");
            if ($bdd->affected() != 1) {
                elog($bdd->affected()." champ(s) affecté(s) par la requête du fichier ".__FILE__." à la ligne ".__LINE__.", données : fondateur = ".$this->fondateur, 2);
            }
            //On ajout l'astéroide
            $bdd->query("INSERT INTO $table_alliances (".implode(', ', $outNomChamps).") VALUES (".implode(', ', $outValeurs).");");
            if ($bdd->affected() != 1) {
                elog($bdd->affected()." champ(s) affecté(s) par la requête du fichier ".__FILE__." à la ligne ".__LINE__.", données : outNomChamps = ".serialize($outNomChamps)." ; outValeurs = ".serialize($outValeurs), 2);
            }
            $bdd->deconnexion();
        } else {
            $out = array();
            $bdd = new BDD();
            foreach ($this->modif as $modif) {
                //On gère les champs variables tableaux
                if (is_array($modif)) {
                    if ($modif[0] == "batiments") {
                        $calc = dDonnees::nameVAR("alli_batiments");
                    } else {
                        $calc = dDonnees::nameVAR($modif[0]);
                    }

                    if (!isset(${$calc.'VAR'})) {
                        global ${$calc.'VAR'};
                    }
                    if (empty(${$calc.'VAR'})) {
                        trigger_error('Impossible de trouver les données pour '.$modif[0], E_USER_ERROR);
                    }

                    $out[] = ${$calc.'VAR'}[$modif[1]]." = ".$this->{$modif[0]}[$modif[1]];
                } elseif ($modif == "force") {
                    $out[] = "metal = ".$this->metal;
                    $out[] = "cristal = ".$this->cristal;
                    $out[] = "hydrogene = ".$this->hydrogene;
                } elseif (!is_array($this->{$modif}) && !is_object($this->{$modif})) {
                    $bdd->escape($this->{$modif});
                    if (is_int($this->{$modif}) || is_float($this->{$modif})) {
                        $out[] = $modif." = ".$this->{$modif};
                    } else {
                        $out[] = $modif." = '".$this->{$modif}."'";
                    }
                } else {
                    if ($modif != "coeff_bat" && $modif != "vaisseaux" && $modif != "terrestres" && $modif != "casernes" && $modif != "technologies" && $modif != "batiments") {
                        $prep = serialize($this->{$modif});
                        $bdd->escape($prep);
                        $out[] = $modif." = '$prep'";
                    } else {
                        $calc = dDonnees::nameVAR($modif);

                        if (!isset(${$calc.'VAR'})) {
                            global ${$calc.'VAR'};
                        }

                        foreach ($this->{$modif} as $j => $value) {
                            $out[] = ${$calc.'VAR'}[$j]." = ".$value;
                        }
                    }
                }
            }
            if (!empty($out)) {
                $sql = "UPDATE $table_alliances SET ".implode(', ', $out)." WHERE id = ".$this->id.";";
                if (DEBUG) {
                    echo '<br /><br />'.$sql;
                }
                $bdd->query($sql);
                if ($bdd->affected() != 1) {
                    elog($bdd->affected()." champ(s) affecté(s) par la requête du fichier ".__FILE__." à la ligne ".__LINE__.", données : out = ".serialize($out), 2);
                }
            }

            $bdd->deconnexion();
            parent::__destruct();
        }
    }
}
