<?php
App::uses('AppModel', 'Model');
App::uses('CakeSession', 'Model/Datasource');

App::uses('Modifier', 'Model');
App::uses('Safeguard', 'Model');
App::uses('ProgramChildPlacement', 'Model');
App::uses('WorkoutChild', 'Model');
/**
 * ProgramChild Model
 *
 * @property Program $Program
 * @property Race $Race
 * @property Sport $Sport
 */
class ProgramChild extends AppModel
{
	public $actsAs = array('Training', 'AddRace', 'Containable');

	public function __construct($id = false, $table = null, $ds = null)
	{
		parent::__construct($id, $table, $ds);
	}
/**
 * Use database config
 *
 * @var string
 */
	public $useDbConfig = 'gearhead';

/**
 * Display field
 *
 * @var string
 */
	public $displayField = 'name';

/**
 * Validation rules
 *
 * @var array
 */
	public $validate = array(
		'name' => array(
			'notEmpty' => array(
				'rule' => 'notBlank',
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
		'program_id' => array(
			'numeric' => array(
				'rule' => array('numeric'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
			'notEmpty' => array(
				'rule' => 'notBlank',
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
		'race_distance' => array(
			'numeric' => array(
				'rule' => array('numeric'),
				//'message' => 'Your custom message here',
				'allowEmpty' => true,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
			'notEmpty' => array(
				'rule' => 'notBlank',
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
			'range' => array(
				'rule' => array('range', 0, 80001),
				'message' => 'The Distance must be between 1 and 80000.',
			)
		),
		'trainingweek' => array(
			'numeric' => array(
				'rule' => array('numeric'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
			'notEmpty' => array(
				'rule' => 'notBlank',
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
		'date' => array(
			'date' => array(
				'rule' => array('date'),
				'message' => 'Please check the date and do it again',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
			'check' => array
			(
				'rule' => array('checkDate'),
				'message' => 'Race Date is not in the Range of Program Dates.'
			),
		),
		'visible' => array(
			'boolean' => array(
				'rule' => array('boolean'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
		'race_id' => array(
			'numeric' => array(
				'rule' => array('numeric'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
			'notEmpty' => array(
				'rule' => 'notBlank',
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
		'sport_id' => array(
			'numeric' => array(
				'rule' => array('numeric'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
			'notEmpty' => array(
				'rule' => 'notBlank',
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
	);

	//The Associations below have been created with all possible keys, those that are not needed can be removed

/**
 * belongsTo associations
 *
 * @var array
 */
	public $belongsTo = array(
		'Program' => array(
			'className' => 'Program',
			'foreignKey' => 'program_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
		'Race' => array(
			'className' => 'Race',
			'foreignKey' => 'race_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
		'Sport' => array(
			'className' => 'Sport',
			'foreignKey' => 'sport_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		)
	);
/**
 * hasMany associations
 *
 * @var array
 */
	public $hasMany = array(
		'WorkoutChild' => array(
			'className' => 'WorkoutChild',
			'foreignKey' => 'program_child_id',
			'dependent' => false,
			'conditions' => '',
			'fields' => '',
			'order' => '',
			'limit' => '',
			'offset' => '',
			'exclusive' => '',
			'finderQuery' => '',
			'counterQuery' => ''
		),
	);

	public function checkDate($check)
	{
		return $this->getTrainingweek($this->data['ProgramChild']['date'], $this->data['ProgramChild']['program_id']);
	}

	public function afterValidate()
	{
		$workoutChildren = $this->_generateWorkoutChildren();
	}

	public function	afterSave($created, $options = array())
	{
		if($created)
		{
			$workoutChildren = $this->_generateWorkoutChildren();
			$WorkoutChildModel = new WorkoutChild();
			$WorkoutChildModel->create();
			$WorkoutChildModel->saveMany($workoutChildren);
		}
	}

	private function _generateWorkoutChildren()
	{
		if($this->getLastInsertId())
		{
			$programChildId = $this->getLastInsertId();
		}
		else
		{
			$programChildId = 2;
		}
		//fix only for afterValidate
		$raceDistance = ($this->data['ProgramChild']['race_distance'] > 0) ? (int)$this->data['ProgramChild']['race_distance'] : 1;
		$date = $this->data['ProgramChild']['date'];
		$programId = $this->data['ProgramChild']['program_id'];
		$taperLength = $this->data['ProgramChild']['taper_length'];
		$sportId = $this->getSportId($this->data['ProgramChild']['race_type']);
		$raceId = $this->getRaceId($this->data['ProgramChild']['race_type'], $raceDistance);

		$heartRates = $this->getHeartRates($programId, CakeSession::read('Auth.User.date_of_birth'));

		$this->data['ProgramChild']['race_distance'] = $raceDistance;
		$this->data['ProgramChild']['trainingweek'] = $this->getTrainingweek($date, $programId);
		$this->data['ProgramChild']['visible'] = 1;
		$this->data['ProgramChild']['sport_id'] = $sportId;
		$this->data['ProgramChild']['race_id'] = $raceId;
		$this->data['ProgramChild']['heart_min'] = $heartRates['Race'][$raceId]['min'];
		$this->data['ProgramChild']['heart_max'] = $heartRates['Race'][$raceId]['max'];

		

		$workouts = $this->addRaceWeek($programId, $programChildId, $taperLength, $date, $heartRates, $raceId, $sportId);

		return $workouts;
	}

	public function findAndSortByDate($date, $userId)
	{
		$start = clone $date; $start->modify('- 12 days');
		$end = clone $date; $end->modify('next month'); $end->modify('+ 12 days');

		$programs = $this->find('all',array
		(
			'conditions' => array
			(
				'Program.user_id' => $userId,
				'Program.visible' => true,
				'ProgramChild.visible' => true,
			),
			'contain' => array
			(
				'Program',
				'WorkoutChild' => array(
					'conditions' => array(
						//'WorkoutChild.date <=' => $date->format('Y-m-t'),
						'WorkoutChild.date >=' => $start->format('Y-m-d'),
						'WorkoutChild.date <=' => $end->format('Y-m-d'),
					),
					'Sport' => array(
						'name',
						'value',
						'Measurement' => array(
							'value',
							'symbol'
						),
					),
					'Zone',
					'TassPlacementType',
					'StrengthType' => array(
						'name',
						'value',
					),
				),
				'Race',
			),
			'order' => array(
				'ProgramChild.date' => 'desc',
			),
		));

		$entries = array();
		$date = new DateTime();
		//$tapers = array('4t1', '4bt1', '4rt1', '4t2', '4t3', '10t1', '10bt1', '10rt1', '10t2', '10t3');

		foreach($programs as $key => $program)
		{
			$date->modify($program['ProgramChild']['date']);

			if(!isset($entries[$date->format('Y-n-j')]['addrace']))
			{
				$entries[$date->format('Y-n-j')]['addrace'] = array();
			}
			
			$entries[$date->format('Y-n-j')]['addrace'] = $program['ProgramChild'];

			foreach($program['WorkoutChild'] as $workout)
			{
				$date->modify($workout['date']);

				if(!isset($entries[$date->format('Y-n-j')][$workout['Sport']['value']]))
				{
					$entries[$date->format('Y-n-j')][$workout['Sport']['value']] = array();
				}

				$workout['race_id'] = $program['ProgramChild']['race_id'];

				$entry = $entries[$date->format('Y-n-j')][$workout['Sport']['value']];

				if(isset($workout['TassPlacementType']['value']) && $workout['TassPlacementType']['value'] == 'tu1' && $workout['date'] == '2015-07-01')
				{
					#$this->log($workout);
				}

				if(isset($entry['TassPlacementType']['value']) && $entry['TassPlacementType']['value'] == '4t4' && $program['Race']['value'] == 'half-ironman')
				{
				}

				if($workout['date'] == '2015-07-01' && $workout['Sport']['value'] == 'bike')
				{
					$this->log($workout);
					$this->log($program['ProgramChild']['name']);
				}

				if(isset($entry['taper']) && $entry['taper'] == 1)
				{
					if(isset($workout['TassPlacementType']['value']) && $workout['TassPlacementType']['value'] == 'tu1')
					{
						$entries[$date->format('Y-n-j')][$workout['Sport']['value']] = $workout;
						#$this->log($workout);
					}
					elseif(isset($workout['taper']) && $workout['taper'] == 1)
					{
						$entries[$date->format('Y-n-j')][$workout['Sport']['value']] = $workout;
					}
				}
				else
				{
					$entries[$date->format('Y-n-j')][$workout['Sport']['value']] = $workout;
				}

				/*
				if(isset($workout['TassPlacementType']['value']))
				{
					if(in_array($workout['TassPlacementType']['value'], $tapers))
					{
					}
					else
					{
						$entries[$date->format('Y-n-j')][$workout['Sport']['value']] = $workout;
					}
				}
				else
				{
					$entries[$date->format('Y-n-j')][$workout['Sport']['value']] = $workout;
				}
				 */


				/*
				if(isset($entry['taper']) && $entry['taper'] == 1)
				{
					$entries[$date->format('Y-n-j')][$workout['Sport']['value']] = $workout;
				}
				else
				{
				}
				 */
			}
			 
		}

		//$this->log($entries);

		return $entries;
	}

	public function afterDelete()
	{
		$this->WorkoutChild->deleteAll(
			array('WorkoutChild.program_child_id' => $this->id),
			false
		);
	}

}
