<?

class generating {

	private $sql;

	private $statement;

	public function __construct() {
		$this->sql = $data->main_instance;
		$this->statement = $data->statement;
	}

	public function get_media_from_item($library_item_id) {
		$query = 'SELECT * FROM library WHERE parent_id = ? AND is_active = 1';
		$sub_items = $this->sql->get_rows($query, [$library_item_id]);

		$media_items = [];

		foreach($sub_items as $sub_item) {
			if($sub_item['is_folder'] == 1) {
				$media_items = $object->concat($media_items, $this->get_media_from_item($sub_item['id']));
			} else {
				$media_items[] = $sub_item;
			}
		}

		return $media_items;
	}

	public function get_minimum_play_count($media_items) {
		$minimum_play_count = (-1);

		$results = [];

		foreach($media_items as $media_item) {
			$count = 0;
			if(!$object->isset($media_item['watch_count'])) {
				$query = 'SELECT COUNT(*) as count FROM watch_log WHERE library_item_id = ?';
				$count = $this->sql->get_row($query, [$media_item['id']])['count'];

				$media_item['watch_count'] = $count;
			} else {
				$count = $media_item['watch_count'];
			}

			if($count < $minimum_play_count || $minimum_play_count == (-1)) {
				$minimum_play_count = $count;
			}
		}

		foreach($media_items as $media_item) {
			if($media_item['watch_count'] <= $minimum_play_count) {
				$results[] = $media_item;
			}
		}

		return $results;
	}

	public function generate_playlist($id, $iterations=1) {
		$query = 'SELECT * FROM playlists WHERE id = ?';
		$playlist_template = $this->sql->get_row($query, [$id]);

		$content = [$object->strings->hashtag().'EXTM3U'];

		$set_library_items = [];

		if($playlist_template != NULL) {
			if($playlist_template['type'] == 1) {
				$query = 'SELECT * FROM template_items WHERE playlist_template_id = ?';
				$template_items = $this->sql->get_rows($query, [$id]);

				$sorting = NULL;

				if($playlist_template['sorting'] != NULL && $object->strings->strlen($playlist_template['sorting']) > 0) {
					$sorting = $object->fromJSON($playlist_template['sorting']);
				}

				$set_template_items_index = $object->create();

				foreach($template_items as $template_item) {
					$set_template_items_index[$template_item['id']] = $template_item;
				}

				$set_template_items = [];

				foreach($sorting as $sort_id) {
					$set_template_items[] = $set_template_items_index[$sort_id];
				}

				$count = 0;

				$results = [];

				$set_template_items_by_index = $object->create();

				foreach($set_template_items as $template_item) {
					$media_items = [];
					if($template_item['library_item_id'] != (-1) && $template_item['library_item_id'] != NULL) {
						if(!$object->isset($set_template_items_by_index[$template_item['library_item_id']])) {

							$media_items = $this->get_media_from_item($template_item['library_item_id']);
							$object->sort($media_items, function($a, $b) {
								return $object->strings->compare($object->strings->lower($a['relativepath']), $object->strings->lower($b['relativepath']));
							});

							$set_template_items_by_index[$template_item['library_item_id']] = $media_items;
						} else {
							$media_items = $set_template_items_by_index[$template_item['library_item_id']];
						}
					}
					$template_item['media'] = $media_items;
				}

				while($count < $iterations) {
					foreach($set_template_items as $template_item) {
						if($template_item['media']->length > 0) {

							$selection = $this->get_minimum_play_count($template_item['media']);

							if($template_item['random'] == 1) {
								$index = $math->random_int($selection->length);
							} else {
								$index = 0;
							}


							$selection_item = $selection[$index];

							$results[] = $selection_item;

							$set_library_items[] = $selection_item;

							$object->add_to_watch_log($selection_item['id'], $selection_item);
						}
					}

					$count = $count+1;
				}

				$paths = [];

				$locations = $object->get_locations();

				foreach($results as $result_item) {
					$added = false;
					foreach($locations as $location) {
						if(!$added) {
							$combined = $files->append_path($location, $result_item['relativepath']);
							if($files->exists($combined)) {
								$paths[] = ['path' => $combined, 'title' => $result_item['title']];
								$added = true;
							}
						}
					}
				}

				foreach($paths as $path) {
					$content[] = $object->strings->hashtag().'EXTINF:1,'.$path['title'];
					$content[] = $path['path'];
				}
			} else {
				$color_connections = $playlist_template['sorting'];

				if($color_connections != NULL && $object->strings->strlen($color_connections) > 0) {
					$color_connections = $object->fromJSON($color_connections);

					$all_tags = $object->create();

					$set_connections = $object->create();

					foreach($color_connections as $key => $value) {
						$split = $object->strings->split($key, '-');

						$all_tags[$split[0]] = true;
						$all_tags[$split[1]] = true;

						if(!$object->isset($set_connections[$split[0]])) {
							$set_connections[$split[0]] = [
								'connections' => [],
								'media' => []
							];
						}
						$set_connection = $set_connections[$split[0]]['connections'];
						$counter_set = 0;
						while($counter_set < $value) {
							$set_connection[] = $split[1];
							$counter_set = $counter_set + 1;
						}

						if(!$object->isset($set_connections[$split[1]])) {
							$set_connections[$split[1]] = [
								'connections' => [],
								'media' => []
							];
						}
						$set_connection = $set_connections[$split[1]]['connections'];
						$counter_set = 0;
						while($counter_set < $value) {
							$set_connection[] = $split[0];
							$counter_set = $counter_set + 1;
						}
					}

					$all_tags = $object->keys($all_tags);

					$random_start_index = $math->random_int($all_tags->length);

					$start_tag = $all_tags[$random_start_index];

					$current_tag = $start_tag;

					$count = 0;

					$total_count = $iterations * 50;

					$playlist_sources = [];
					/*$query = 'SELECT * FROM playlist_sources WHERE playlist_template_id = ?';
					$playlist_sources = $this->sql->get_rows($query, [$id]);*/

					foreach($all_tags as $tag) {
						$library_items = $this->get_library_items_from_tag($tag, $playlist_sources);


						$media = [];

						foreach($library_items as $library_item) {
							$media_items = $this->get_media_from_item($library_item['id']);

							$media = $object->concat($media, $media_items);
						}


						$object->sort($media_items, function($a, $b) {
							return $object->strings->compare($object->strings->lower($a['relativepath']), $object->strings->lower($b['relativepath']));
						});

						$set_connections[$tag]['media'] = $media;
					}

					$results = [];

					while($count < $total_count) {
						$tag_connection = $set_connections[$current_tag];
						if($tag_connection['media']->length > 0) {
							$selection = $this->get_minimum_play_count($tag_connection['media']);

							$media_index = $math->random_int($selection->length);


							$media_item = $selection[$media_index];

							$set_library_items[] = $media_item;

							$results[] = $media_item;

							$object->add_to_watch_log($media_item['id'], $media_item);

							if($tag_connection['connections']->length == 0) {
								$random_tag_index = $math->random_int($all_tags->length);
								$current_tag = $all_tags[$random_tag_index];
							} else {
								$random_tag_index = $math->random_int($tag_connection['connections']->length);
								$current_tag = $tag_connection['connections'][$random_tag_index];
							}
						}
						$count = $count+1;
					}


					$paths = [];

					$locations = $object->get_locations();

					foreach($results as $result_item) {
						$added = false;
						foreach($locations as $location) {
							if(!$added) {
								$combined = $files->append_path($location, $result_item['relativepath']);
								if($files->exists($combined)) {
									$paths[] = ['path' => $combined, 'title' => $result_item['title']];
									$added = true;
								}
							}
						}
					}

					foreach($paths as $path) {
						$content[] = $object->strings->hashtag().'EXTINF:1,'.$path['title'];
						$content[] = $path['path'];
					}
				}
			}
		}

		$date_value = $date->get_date('default', 0, 0, 0);

		return [
			'name' => $playlist_template['title'].'-'.$date_value,
			'content' => $object->strings->join($content, $object->strings->get_newline()),
			'library_items' => $set_library_items
		]; 
	}

	public function get_library_items_from_tag($tag, $sources) {
		if($sources->length > 0) {
			return [];
		} else {
			$results = [];

			$query = 'SELECT * FROM library WHERE is_template_item = 1 AND tags LIKE ?';
			$library_items = $this->sql->get_rows($query, ['%'.$tag.'%']);

			return $library_items;
		}
	}

}

?>