<?

class cinema_indexing extends live_indexing {



	public function __construct($base) {
		$this->base = $base;
		$this->statement = new statement();

		$this->data = $data->fetch('cinema');
	}

	public $locations;


	public $extensions = ['m4v', 'mp4', 'mkv', 'avi', 'wmv', 'mov', 'flv', '3gp', 'mpg', 'ts', 'rm', 'swf'];

	public function init($locations) {
		$self = $this;
		if($this->in_progress) {
			return false;
		}
		$this->in_progress = true;

		$object->log('init live indexing Cinema');


		if($locations->length == 0) {
			return NULL;
		}


		$this->locations = $locations;

		$content_type = 'public.movie';

		$query_string = 'kMDItemContentTypeTree CONTAINS[cd] "public.movie" OR kMDItemContentTypeTree CONTAINS[cd] "dyn.ah62d4rv4ge804450" OR kMDItemFSName LIKE[cd] "*.m4v" OR kMDItemFSName LIKE[cd] "*.mp4" OR kMDItemFSName LIKE[cd] "*.mkv" OR kMDItemFSName LIKE[cd] "*.avi" OR kMDItemFSName LIKE[cd] "*.wmv" OR kMDItemFSName LIKE[cd] "*.mov" OR kMDItemFSName LIKE[cd] "*.flv" OR kMDItemFSName LIKE[cd] "*.3gp" OR kMDItemFSName LIKE[cd] "*.mpg" OR kMDItemFSName LIKE[cd] "*.ts" OR kMDItemFSName LIKE[cd] "*.rm" OR kMDItemFSName LIKE[cd] "*.swf"';

		$variables = [];

		$files->search->stop_search_b();

		$set_locations = [...$locations];

		$this->make_accessible_multiple($set_locations, function() {
			$files->search->new_search_b($query_string, $variables, $locations, function($results) {
				if($results != NULL) {
					$self->run_update($results);
				}
			}, function($results) {
				$object->log('in callback2');
				/*$object->log('in callback2');
				$self->run_update($results);*/
			});
		});
	}

	

	public function initial_update($results) {
		$object->send('app.main_settings.highlight_indexing_in_progress(data)', ['data' => true]);
		$object->set_app_property('indexing_in_progress', true);
		$this->base->indexing_dictionary['cinema'] = true;
		$this->last_updated_results = $results;

		$performed_change = false;

		$episode_index_a = $object->create();

		$query = 'SELECT * FROM movies WHERE filesize IS NULL';
		$movies = $this->data->get_rows($query, []);
		foreach($movies as $movie) {
			$episode_index_a[$movie['filepath']] = $movie;
		}

		foreach($results as $episode) {
			if($object->isset($episode_index_a[$episode['kMDItemPath']])) {
				$episode_values = $episode_index_a[$episode['kMDItemPath']];
				$this->_movie([
					'id' => $episode_values['id'],
					'filesize' => $object->to_string($episode['kMDItemFSSize'])
				]);
			}
		}

		$query = 'SELECT * FROM movies';
		$all_episodes = $this->data->get_rows($query, []);



		$set_episode_index = $object->create();

		foreach($all_episodes as $episode) {
			$components = $files->remove_path_component($episode['filepath']);
			$filename = $components['last_component'];
			$index_id = $filename.'-'.$episode['filesize'];

			if(!$object->isset($set_episode_index[$index_id])) {
				$set_episode_index[$index_id] = [];
			}

			$set_episode_index[$index_id][] = $episode;
		}

		$mark_exists = $object->create();

		foreach($results as $episode) {
			$components = $files->remove_path_component($episode['kMDItemPath']);

			$filename = $components['last_component'];

			$index_id = $filename.'-'.$episode['kMDItemFSSize'];

			
			$path = $episode['kMDItemPath'];

			$mark_exists[$index_id] = $path;

			if(!$object->isset($set_episode_index[$index_id])) {
				$episode_id = $this->_movie([
					'filepath' => $path,
					'filesize' => $episode['kMDItemFSSize'],
					'filename' => $filename
				]);
				$performed_change = true;
			} else {
				$same_paths = false;
				foreach($set_episode_index[$index_id] as $episode_set_values) {
					if($episode_set_values['filepath'] == $path) {
						$same_paths = true;
					}
				}
				if(!$same_paths) {
					foreach($set_episode_index[$index_id] as $episode_set_values) {
						if(!$files->exists($episode_set_values['filepath'])) {
							$update_values = [
								'id' => $episode_set_values['id'],
								'filepath' => $path
							];
							$this->_movie($update_values);
							$performed_change = true;
						}
					}
				}
			}
		}

		foreach($set_episode_index as $index_value => $episode_item) {
			foreach($episode_item as $item_values) {
				if(!$files->exists($item_values['filepath'])) {
					$this->delete_movie($item_values['id']);
					$performed_change = true;
				}
			}

			if(!$object->isset($mark_exists[$index_value])) {
				foreach($episode_item as $item_values) {
					$this->delete_movie($item_values['id']);
					$performed_change = true;
				}
			} else {
				foreach($episode_item as $item_values) {
					if($item_values['path'] != $mark_exists[$index_value]) {
						$this->delete_movie($item_values['id']);
						$performed_change = true;
					}
				}
			}
		}

		if($performed_change) {
			$this->clean_duplicates();
			/*$self = $this;
			$wrap_duplicates = async function() {
				$self->clean_duplicates();
			};
			$wrap_duplicates();*/
		}

		$this->update_in_progress = false;
		$this->base->indexing_dictionary['cinema'] = false;
		if($performed_change) {
			$object->send('app.view_update(data)', ['data' => true]);
		}
		if(!$this->base->indexing_dictionary['tv']) {
			$object->send('app.main_settings.highlight_indexing_in_progress(data)', ['data' => false]);
			$object->set_app_property('indexing_in_progress', false);
		}
		$this->in_progress = false;
		
		/*$this->run_stored_update();*/
	}

	public function run_stored_update() {
		$self = $this;
		/*if(!$this->update_in_progress && $this->stored_results != NULL) {
			$results = $this->stored_results;
			$this->stored_results = NULL;
			
			$files->search->restart_search_b();
		}*/
	}

	public function delete_movie($id) {
		$query = 'DELETE FROM movies WHERE id = ?';
		$this->data->execute($query, [$id]);
	}

	public function _movie($v) {
		$insert = $this->data->statement->generate($v, 'movies');
		$this->data->_($insert, $v);
		$id = $this->data->last_id($v);
		return $id;
	}



	public function clean_duplicates() {
		$query = 'SELECT * FROM movies'; /*as a WHERE (SELECT COUNT(*) as count FROM movies as e WHERE e.filepath = a.filepath) > 1*/
		$rows = $this->data->get_rows($query, []);
		foreach($rows as $row) {
			$query = 'SELECT * FROM movies WHERE filepath = ?';
			$episodes = $this->data->get_rows($query, [$row['filepath']]);
			if($episodes->length > 1) {
				$max_size = (-1);
				$set_id = NULL;
				foreach($episodes as $episode) {
					if($episode['filesize'] > $max_size) {
						$max_size = $episode['filesize'];
						$set_id = $episode['id'];
					}
				}
				if($set_id != NULL) {
					foreach($episodes as $episode) {
						if($episode['id'] != $set_id) {
							$query = 'DELETE FROM movies WHERE id = ?';
							$this->data->execute($query, [$episode['id']]);
						}
					}
				}
			}
		}
		$query = 'DELETE FROM movies WHERE filepath IS NULL';
		$this->data->execute($query, []);
	}
}

?>