<?php
namespace App\Model\Table;

use App\Model\Entity\Infection;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
use MedidasDispersao\MedidasDispersao;

require_once ROOT . DS . "vendor" . DS . "Zurubabel" . DS . "MedidasDispersao.php";

/**
 * Infections Model
 *
 * @property \Cake\ORM\Association\BelongsTo $Hospitalizations
 * @property \Cake\ORM\Association\BelongsToMany $Cultures
 */
class InfectionsTable extends Table
{

    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('infections');
        $this->displayField('id');
        $this->primaryKey('id');

        $this->addBehavior('Timestamp');

        $this->belongsTo('Hospitalizations', [
            'foreignKey' => 'hospitalization_id',
            'joinType' => 'INNER',
        ]);
        $this->belongsToMany('Cultures', [
            'foreignKey' => 'infection_id',
            'targetForeignKey' => 'culture_id',
            'joinTable' => 'cultures_infections',
        ]);
    }

    /**
     * Default validation rules.
     *
     * @param \Cake\Validation\Validator $validator Validator instance.
     * @return \Cake\Validation\Validator
     */
    public function validationDefault(Validator $validator)
    {
        $validator
            ->integer('id')
            ->allowEmpty('id', 'create');

        $validator
            ->requirePresence('type', 'create')
            ->notEmpty('type');

        $validator
            ->requirePresence('gravity', 'create')
            ->notEmpty('gravity');

        $validator
            ->boolean('is_IRAS')
            ->allowEmpty('is_IRAS');

        $validator
            ->allowEmpty('IRAS_description');

        $validator
            ->allowEmpty('classifcation');

        $validator
            ->boolean('is_active')
            ->allowEmpty('is_active');

        $validator
            ->boolean('identificacao_agente')
            ->allowEmpty('identificacao_agente');

        return $validator;
    }

    public function getRelatorioData($hospitalizations, $diagnostics, $date_before, $date_after)
    {
        $calc_obj = new MedidasDispersao();

        $data =
            [
            'total_internacoes' => 0,
            'arr_internacoes_admisao_infeccao' => [],
            'tot_internacoes_admisao_infeccao' => 0,
            'percen_internacoes_admisao_infeccao' => 0,

            //COMPROVAÇÃO MICROBIOLÓGICA: VALOR ABSOLUTO E PERCENTUAL NO TOTAL DE INFECÇOES/SEPSES
            'tot_infeccoss_identificacao_agente' => 0,
            'tot_sepse' => 0,
            'percen_identificacao_agente_por_sepse' => 0,

        ];

        foreach ($diagnostics as $diagnostic)
        {
            if (in_array($diagnostic->id, $data['arr_internacoes_admisao_infeccao']) == false)
            {
                array_push($data['arr_internacoes_admisao_infeccao'], $diagnostic->id);
                $data['tot_internacoes_admisao_infeccao']++;
            }
        }

        foreach ($hospitalizations as $hospitalization)
        {
            $data['total_internacoes']++;

            foreach ($hospitalization['sepse_protocols'] as $key => $sepse)
            {
                if ($sepse['reconhecimento_sepse_data'] >= $date_before &&
                    $sepse['reconhecimento_sepse_data'] <= $date_after
                )
                {
                    $data['tot_sepse']++;
                }
            }
            foreach ($hospitalization["infections"] as $key_1 => $infection)
            {
                $register_arr = (array) $infection;
                $i = 0;

                if ($infection['identificacao_agente'])
                {
                    $data['tot_infeccoss_identificacao_agente']++;
                }

                // if ($bundle['date_instalation'] >= $date_before &&
                //     $bundle['date_instalation'] <= $date_after
                // )
                // {

                //     foreach ($register_arr as $key_2 => $value_2)
                //     {
                //         $i++;
                //         if ($i == 2) //acessa as propriades do obj
                //         {
                //             foreach ($value_2 as $key_3 => $value_3)
                //             {
                //                 //$data[$key_3] = $value_3;
                //                 formatArr($value_3, $data, $key_3);
                //             }
                //         }
                //     }
                // }
            }

            foreach ($hospitalization["cultures"] as $key => $culture)
            {
                // if ($supportive_measure['data_inicio'] >= $date_before &&
                //     $supportive_measure['data_termino'] <= $date_after
                // )
                // {
                //     $data["tot_dispositivos_inseridos"]++;
                //     if (stripos($supportive_measure['type'], 'cateter vesical') !== false)
                //     {
                //         $data['tot_procedimento_cateter_vesical']++;

                //         if (in_array($hospitalization->id, $data['arr_internacao_procedimento_vesical']) == false)
                //         {
                //             array_push($data['arr_internacao_procedimento_vesical'], $hospitalization->id);
                //             $data['tot_internacao_procedimento_vesical']++;
                //         }
                //     }
                // }
            }
        }

        foreach ($data as $key => $value)
        {
            $marcados = 0;

            if (isset($data[$key]['percentual']) && isset($data[$key]['arr']))
            {
                $len = count($data[$key]['arr']);

                for ($i = 0; $i < $len; $i++)
                {
                    if ($data[$key]['arr'][$i] || $data[$key]['arr'][$i] !== 0)
                    {
                        $marcados++;
                    }
                }

                $data[$key]['total'] = count($data[$key]['arr']);
                $data[$key]['soma'] = 0;
                $data[$key]['percentual'] = $calc_obj->calculate_percentage($marcados, $data['total_de_bundles']);
                $data[$key]['media'] = $calc_obj->calc_average($data[$key]['arr']);
                $data[$key]['mediana'] = $calc_obj->calculate_median($data[$key]['arr']);
                $data[$key]['desvio_padrao'] = $calc_obj->standard_deviation($data[$key]['arr']);

                //calcula o total
                if (count($data[$key]['arr']) > 0)
                {
                    foreach ($data[$key]['arr'] as $attr)
                    {
                        if (is_numeric($attr))
                        {
                            $data[$key]['soma'] += $attr;
                        }
                    }
                }
            }
        }

        if ($data['tot_internacoes_admisao_infeccao'] > 0 &&
            $data['total_internacoes'] > 0)
        {
            $data['percen_internacoes_admisao_infeccao'] = ($data['tot_internacoes_admisao_infeccao'] * 100) / $data['total_internacoes'];
            $data['percen_internacoes_admisao_infeccao'] = round($data['percen_internacoes_admisao_infeccao'], 2);
        }

        if ($data['tot_infeccoss_identificacao_agente'] > 0 &&
            $data['tot_sepse'] > 0)
        {
            $data['percen_identificacao_agente_por_sepse'] = ($data['tot_infeccoss_identificacao_agente'] * 100) / $data['tot_sepse'];
            $data['percen_identificacao_agente_por_sepse'] = round($data['percen_identificacao_agente_por_sepse'], 2);
        }

        return $data;
    }

    /**
     * Returns a rules checker object that will be used for validating
     * application integrity.
     *
     * @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
     * @return \Cake\ORM\RulesChecker
     */
    public function buildRules(RulesChecker $rules)
    {
        $rules->add($rules->existsIn(['hospitalization_id'], 'Hospitalizations'));
        return $rules;
    }
}
