<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Controlador Competitor, gestiona la creacion de competidores, edicion, etc
 * Created by PhpStorm.
 * User: Pablo García Sanz
 * Date: 02/10/2017
 * Time: 17:23
 */

class Competitor extends CI_Controller

{
    private $language;
    private $text_competitors;
    const PERPAGE = 5;
    const NUM_LINKS = 10;

    /**
     * Competitor constructor.
     * Constructor de la clase Competitor. Inicializa el lenguaje en funcion de la sesion
     * Comprueba que este iniciada la sesión del usuario con rol delegado
     */
    public function __construct()
    {
        parent::__construct();
        include "application/src/CompetitorModelo.php";
        include "application/src/Pagination.php";
        $this->load->model('competitorModel');
        $this->load->model('ageGroupModel');
        $this->load->model('weightModel');
        $this -> language = $this -> session -> userdata('language');
        $this -> text_competitors = $this -> get_text_competitors($this -> language);
    }

    /**
     * Funcion del controlador que muestra los competidores que esten registrados en la aplicación
     */
    public function index()
    {

        $this->load->library('pagination');
        $this->load->library('table');

        $competitors = $this->competitorModel->getAllCompetitors();


        $c= $this->competitorModel->getCompetitors(self::PERPAGE, $this->uri->segment(3));

        $data['competitors'] =$this -> competitorWithPuesto($c);
        $data['agegroup'] = $this->ageGroupModel->getAgeGroupTypes();
        $data['weights'] = $this->weightModel->getAllWeights();
        $data['text_competitors'] = $this ->text_competitors;

        $pagination = new Pagination(base_url().'competitor/index/',sizeof($competitors),self::PERPAGE,self::NUM_LINKS);
        $pagination -> init_pagination();

        $this->load->view('Estructura/header_principal');
        $this->load->view('Competitors/competitors', $data);
        $this->load->view('Estructura/footer');
    }

    /**
     * Funcion de búsqueda de competidores en funcion de paraemtros pasado por medio de un post
     * de un formulario
     */
    public function search()
    {
        $this->load->library('pagination');
        $fecha_i = $this->input->get('fecha_inicio');
        $fecha_f = $this->input->get('fecha_fin');
        $agegroup = $this->input->get('agegroup');
        $weight = $this->input->get('weight');

        $weight = $weight == 0 ? '%' : $weight;
        $competitors = $this->competitorModel->getCompetitorsByDate($fecha_i, $fecha_f, $weight, self::PERPAGE, $this->uri->segment(3), $agegroup);
        $data['weights'] = $this->weightModel->getAllWeights();
        $data['competitors'] = $this ->competitorWithPuesto($competitors);
        $data['agegroup'] = $this->ageGroupModel->getAgeGroupTypes();
        $data['text_competitors'] = $this ->text_competitors;

        $pagination = new Pagination(base_url().'competitor/search/',sizeof($this->competitorModel->countRowsCompetitorsBy($fecha_i, $fecha_f, $weight, $agegroup)),self::PERPAGE,self::NUM_LINKS);
        $pagination -> init_pagination();

        $this->load->view('Estructura/header_principal');
        $this->load->view('Competitors/competitors', $data);
        $this->load->view('Estructura/footer');
    }

    private function get_text_competitors($idiom)
    {
        $this->lang->load('competitor_lang', $idiom);
        $data['competitor_sort_text'] = $this->lang->line('competitor_sort_text');
        $data['competitor_date_since'] = $this->lang->line('competitor_date_since');
        $data['competitor_date_until'] = $this->lang->line('competitor_date_until');
        $data['competitor_medal_gold'] = $this->lang->line('competitor_medal_gold');
        $data['competitor_medal_silver'] = $this->lang->line('competitor_medal_silver');
        $data['competitor_medal_bronze'] = $this->lang->line('competitor_medal_bronze');
        $data['competitor_medal_table'] = $this->lang->line('competitor_medal_table');
        $data['competitor_weight'] = $this->lang->line('competitor_weight');
        $data['competitor_toast_date'] = $this->lang->line('competitor_toast_date');
        $data['competitor_toast_date_interval'] = $this->lang->line('competitor_toast_date_interval');

        $data['competitor_name'] = $this->lang->line('competitor_name');
        $data['competitor_surname'] = $this->lang->line('competitor_surname');
        $data['competitor_surname2'] = $this->lang->line('competitor_surname2');



        return $data;

    }

    private function competitorWithPuesto($competitors) {
        $aux = array();
        foreach ($competitors as $competitor) {
            if (!array_key_exists($competitor->dni, $aux)) {
                $c = new CompetitorModelo($competitor->dni,
                    $competitor->nombre,
                    $competitor->apellido1,
                    $competitor->apellido2,
                    $competitor->paisISOA3,
                    $competitor->autonomia,
                    $competitor->provincia,
                    $competitor->email);
                $c->addPuntuacion($competitor->puesto);
                $aux[$competitor->dni] = $c;
            } else {
                $aux[$competitor->dni]->addPuntuacion($competitor->puesto);

            }


        }
        return $aux;
    }


}
