<?php
class ModuleConnection extends AppModel {

	public $useTable = "module_connections";

	public $skipAutoOrdering = true;


	public function getModuleConnections($fatherModule, $sonModule, $father_fk) {

		$connections = $this->find('all', array(
			'conditions' => array(
				'ModuleConnection.father_module' => $fatherModule,
				'ModuleConnection.son_module' => $sonModule,
				'ModuleConnection.father_fk' => $father_fk
			)
		));

		return $connections;
	}


	public function getModuleConnectionsBySonId($fatherModule, $sonModule, $sonFk)
	{

		$connections = $this->find('all', array(
			'conditions' => array(
				'ModuleConnection.father_module' => $fatherModule,
				'ModuleConnection.son_module' => $sonModule,
				'ModuleConnection.son_fk' => $sonFk
			)
		));

		return $connections;
	}

	public function addConnection($data) {

		# Check if there is a connection between two
		$check = $this->find('all', array(
				'conditions' => array(
					'ModuleConnection.father_fk' => $data['father_fk'],
					'ModuleConnection.son_fk' => $data['son_fk'],
					'ModuleConnection.son_module' => $data['son_module'],
					'ModuleConnection.father_module' => $data['father_module'],
				),
				'cache' => false
			)
		);

		# If there is no connection, save data as new connection.
		if(empty($check)) {
			$this->save($data);
		}

		return true;
	}



	public function removeConnection($data) {

		# Check if there is a connection between two
		$check = $this->find('first', array(
				'conditions' => array(
					'ModuleConnection.father_fk' => $data['father_fk'],
					'ModuleConnection.son_fk' => $data['son_fk'],
					'ModuleConnection.son_module' => $data['son_module'],
					'ModuleConnection.father_module' => $data['father_module']
				),
				'cache' => false
			)
		);

		# If there is connection, delete it.
		if(!empty($check)) {
			$this->delete($check['ModuleConnection']['id']);
		}

	}



	public function search($data) {
		$sonInstance = ClassRegistry::init($data['son_module']);
		$normalizedIds = array();

		# If there is fk provided, find products already attached to that id and exclude them from results.
		if(!empty($data['father_fk'])) {
			$olderEntries = $this->find('all', array(
				'fields' => array('ModuleConnection.son_fk'),
				'conditions' => array(
					'ModuleConnection.father_fk' => $data['father_fk'],
					'ModuleConnection.father_module' => $data['father_module']),
				'cache' => false
			));

			# Generate array of ids, suitable for cakes query conditions.
			foreach($olderEntries as $entry) {
				$normalizedIds[] = $entry['ModuleConnection']['son_fk'];
			}
		}

		foreach($data['conditions'] as $key => $condition) {
			$data['conditions'][$key] = str_replace("####field####", $data['term'], $condition);
		}

		$containables = array();
		foreach($data['fields'] as $field) {
			if(preg_match('~^(.*)\.~', $field, $matches)) {
				if($matches[1] != $sonInstance->alias) {
					$containables[$matches[1]] = $matches[1];
				}
			}
		}
		$containables = array_values($containables);

		$findFields = array();


		$conditions =  array(
			'OR' => $data['conditions'],
			"{$sonInstance->alias}.id NOT" => $normalizedIds
		);

		if(!empty($data['strict_conditions'])) {
			foreach($data['strict_conditions'] as $key => $condition) {
				$conditions[$key] = $condition;
			}
		}

		# Find all items that match provided term, but exclude alredy connected
		$matchedConnections = $sonInstance->find('all', array(
			'recursive' => -1,
			'contain' => $containables,
			'fields' => $data['fields'],
			'conditions' => $conditions,
			'cache' => false
		));

		App::import('Helper', 'Format');
		$formatHelper = new FormatHelper(new View());
		foreach($containables as $containable) {
			if($sonInstance->hasOne[$containable]['className'] == 'Upload') {
				foreach($matchedConnections as $index => $connection) {
					$matchedConnections[$index][$containable]['file'] = $formatHelper->image($matchedConnections[$index][$containable], 300, 200, false, array(), true);
				}
			}
		}


		# Generate path to view for each product.
		foreach($matchedConnections as $index => $value) {
			$matchedConnections[$index][$sonInstance->alias]['path'] = "/" . Inflector::tableize($sonInstance->alias) . "/view/" . $value[$sonInstance->alias]['id'];
		}

		return $matchedConnections;
	}


	public function reattachGenerated($generatedHash, $id) {
		return $this->updateAll(array(
			'father_fk' => $id
		),array(
			'father_fk' => $generatedHash
		));
	}

}
