<?php

/**
 * Controlador Combat, gestiona la creacion de combates, edicion, algoritmo de emparejamientos
 * Created by PhpStorm.
 * User: Pablo García Sanz
 * Date: 02/10/2017
 * Time: 17:23
 */
class Combat extends CI_Controller
{
    const WHITE = 'B';
    const BLUE = 'A';
    const AUTO = 'AUTO';

    const LIGA = 1;
    const RANDOM = 2;

    private $language;
    /**
     * Combat constructor.
     * Constructor de la clase Combate. Inicializa el lenguaje en funcion de la sesion
     * Comprueba que este iniciada la sesión del usuario con rol delegado
     */
    function __construct()
    {
        parent::__construct();

        if (!$this->session->has_userdata('user'))
            redirect(base_url() . '?msg=' . SESSION_EXPIRED, 'refresh');

        $this->language = $this->session->userdata('language');
        $this -> load -> model ('competitionModel');
        $this -> load -> model ('combatModel');
        include "application/src/AlgoritmoEmparejamiento/IEmparejamiento.php";
        include "application/src/AlgoritmoEmparejamiento/ContextoCombate.php";
        include "application/src/AlgoritmoEmparejamiento/EmparejamientoLiga.php";
        include "application/src/AlgoritmoEmparejamiento/EmparejamientoAleatorio.php";


    }
    /**
     * Funcion que muestra los pesos que tiene la competción cuyo id
     * es pasado por parametro a la funcion
     * @param $id de la competicion de la cual se quiere mostrar los combates
     */
    public function viewcompetition($id)
    {

        $competition = $this->competitionModel->getCompetition($id);
        $mats = $this->competitionModel->getMatsByCompetitionId($id);
        $data['text_lateral_nav'] = $this -> get_text_lateral_nav($this -> session -> userdata('language'));
        $data['competition'] = $competition;
        $data['mats'] = $mats;
        $data['f_weights'] = $this->competitionModel->getWeigths($id, 'F');
        $data['m_weights'] = $this->competitionModel->getWeigths($id, 'M');
        $this->load->view('Estructura/header_principal');
        $this->load->view('Combats/combat_6-more', $data);
        $this->load->view('Estructura/footer');
    }

    /**
     * Función que controla la creación de un combate, en la competción pasada por parametro
     * @param $idCompetition
     */
    public function create($idCompetition) {
        $mat = $this -> input -> post('mat');
        $competitor1 = $this -> input -> post('competitor1');
        $competitor2 = $this -> input -> post('competitor2');
        $idWeight = $this -> input -> post ('idWeight');
        $phase = $this -> input -> post('fase');
        if($competitor1 == $competitor2) redirect(base_url().'competition/viewcombats/'.$idCompetition.'?idWeight='.$idWeight.'&msg='.ERROR_EQUAL_COMPETITOR);
        try{
            $idCombat = $this -> combatModel -> create($mat,$phase);
            $this -> combatModel -> createScore($idCombat,$competitor1,self::WHITE);
            $this -> combatModel -> createScore($idCombat,$competitor2,self::BLUE);

            redirect(base_url().'competition/viewcombats/'.$idCompetition.'?idWeight='.$idWeight.'&msg='.SUCCESS_CREATE_COMBAT);
        }
        catch (Exception $e) {

        }

    }

    /**
     * Funcion que controla la creacion de combates en la competcion cuyo id es pasado por parametro.
     * Esta funcion del controlador es utilizada para llamar a las distintas implementacion del patron
     * comando-estrategia.
     * @param $idCompetition Id de la competicion de la cual se quiere crear los combates
     */
    public function create_combats($idCompetition) {
        $tipoSorteo = $this -> input -> post('tipoSorteo');

        $competition = $this->competitionModel->getCompetition($idCompetition);
        $mats = $this->competitionModel->getMatsByCompetitionId($idCompetition);
        $id_mat_deafult = $mats[0] -> idTatami;

        $idWeight = $this -> input -> post('idWeight');
        $players = $this -> combatModel -> getCompetitorsByCompetitionAndIdWeight($competition -> fecha ,$idWeight);
        if($tipoSorteo == null) redirect(base_url().'competition/viewcombats/'.$idCompetition.'?idWeight='.$idWeight.'&msg='.NO_SELECT_ALGORITHIM);
        if(sizeof($players ) < 2) redirect(base_url().'competition/viewcombats/'.$idCompetition.'?idWeight='.$idWeight.'&msg='.ERROR_CAN_NOT_GENERATE_COMBATS);

        switch ($tipoSorteo) {
            case self::LIGA:
                $contexto = new ContextoCombate(new EmparejamientoLiga());
                $emparejamientos = $contexto -> emparejar($players);
                foreach ($emparejamientos as $emparejamiento) {
                    $idCombat = $this -> combatModel -> create($id_mat_deafult,self::AUTO);
                    $this -> combatModel -> createScore($idCombat,$emparejamiento[0] -> dni,self::WHITE);
                    $this -> combatModel -> createScore($idCombat,$emparejamiento[1] -> dni,self::BLUE);
                }
                break;
            case self::RANDOM:
                $contexto = new ContextoCombate(new EmparejamientoAleatorio());
                $emparejamientos = $contexto -> emparejar($players);
                foreach ($emparejamientos as $emparejamiento) {
                    $idCombat = $this -> combatModel -> create($id_mat_deafult,self::AUTO);
                    $this -> combatModel -> createScore($idCombat,$emparejamiento[0] -> dni,self::WHITE);
                    $this -> combatModel -> createScore($idCombat,$emparejamiento[1] -> dni,self::BLUE);
                }
                break;
        }
        redirect(base_url().'competition/viewcombats/'.$idCompetition.'?idWeight='.$idWeight.'&msg='.SUCCESS_CREATE_COMBAT);

    }

    /**
     * Función que actualiza el tatami donde se desarrollara el combate
     */
    public function updateMat() {
        $idMat = $this -> input -> post('mat');
        $idCombat = $this -> input -> post('idCombat');
        $idCompetition = $this -> input -> post('idCompetition');
        $idWeight = $this -> input -> post('idWeight');
        try{

            $this -> combatModel -> updateMat($idCombat,$idMat);
            redirect(base_url().'competition/viewcombats/'.$idCompetition.'?idWeight='.$idWeight.'&msg='.SUCCESS_UPDATE_MAT);
        }
        catch (Exception $e) {
            redirect(base_url().'competition/viewcombats/'.$idCompetition.'?idWeight='.$idWeight);
        }

    }

    /**
     * Funcion del controlador que maneja la eliminación de un determinado combate
     */
    public function delete() {
        $idCombat = $this -> input -> post('idCombat');
        $idCompetition = $this -> input -> post('idCompetition');
        $idWeight = $this -> input -> post('idWeight');

        try {
            $this -> combatModel -> delete($idCombat);
            echo base_url().'competition/viewcombats/'.$idCompetition.'?idWeight='.$idWeight.'&msg='.SUCCESS_DELETE_COMBAT;
        }
        catch (Exception $e) {

        }
    }

    /**
     * Función del controlador que gestiona la introducción de la posición de un determinado competidor en una competición
     *
     */
    public function enterPosition() {
      $dni = $this -> input -> post('competitor');
      $idWeight = $this -> input -> post('idWeight');
      $position = $this -> input -> post('position');
      $idCompetition = $this -> input -> post('competition');
      $date = $this -> input -> post('date');

      try {
          $this -> combatModel -> enterPosition($dni,$idWeight,$position,$date);
          redirect(base_url().'competition/viewcombats/'.$idCompetition.'?idWeight='.$idWeight.'&msg='.SUCCESS_ENTER_POSITION);
      }
      catch (Exception $e ) {

      }

    }

    /**
     * Función del controlador que muestra los arbitros disponibles en un determinado combate.
     * @return un json para que pueda ser gestionado en la response de la peticion AJAX
     */
    public function getReferees() {
        $dniW = $this -> input -> post('dniW');
        $dniB = $this -> input -> post('dniB');
        $idMat = $this -> input -> post('idMat');
        $idCompetition = $this -> input -> post('idCompetition');

        echo json_encode( $this -> combatModel -> getReferees($dniW,$dniB,$idCompetition,$idMat));
}
    private function get_text_lateral_nav($language)
    {
        $this->lang->load('nav_lateral_competition_lang', $language);

        $data['nav_lateral_competition_name'] = $this->lang->line('nav_lateral_competition_name');
        $data['nav_lateral_competition_type_of_competition'] = $this->lang->line('nav_lateral_competition_type_of_competition');
        $data['nav_lateral_competition_age_group'] = $this->lang->line('nav_lateral_competition_age_group');
        $data['nav_lateral_competition_date'] = $this->lang->line('nav_lateral_competition_date');
        $data['nav_lateral_competition_community'] = $this->lang->line('nav_lateral_competition_community');
        $data['nav_lateral_competition_province'] = $this->lang->line('nav_lateral_competition_province');

        $data['nav_lateral_competition_referee_inscription'] = $this->lang->line('nav_lateral_competition_referee_inscription');
        $data['nav_lateral_competition_competitor_inscription'] = $this->lang->line('nav_lateral_competition_competitor_inscription');
        $data['nav_lateral_competition_combats'] = $this->lang->line('nav_lateral_competition_combats');

        $data['nav_lateral_competition_choose_sex'] = $this->lang->line('nav_lateral_competition_choose_sex');
        $data['nav_lateral_competition_female'] = $this->lang->line('nav_lateral_competition_female');
        $data['nav_lateral_competition_male'] = $this->lang->line('nav_lateral_competition_male');
        $data['nav_lateral_number_of_mats'] = $this->lang->line('nav_lateral_number_of_mats');

        return $data;

    }

}