<?php
///////////////////////////////////////////////////////////////////////////

require_once 'freetv_vod_category.php';
require_once 'freetv_vod_list_screen.php';

///////////////////////////////////////////////////////////////////////////

class VodCategoryListScreen extends AbstractPreloadedRegularScreen implements UserInputHandler
{
	const ID = 'vod_category_list';
	public function get_handler_id() { return "tv_handler"; }

	public static function get_media_url_str($category_id = null, $subcategory_id = null, $name = null)
	{
		$arr['screen_id'] = self::ID;

		if (!is_null($category_id))
			$arr['category_id'] = $category_id;

		if (!is_null($subcategory_id))
			$arr['subcategory_id'] = $subcategory_id;

		if (!is_null($name))
			$arr['name'] = $name;

		return MediaURL::encode($arr);
	}

	///////////////////////////////////////////////////////////////////////

	private $category_list;
	private $category_index;

	///////////////////////////////////////////////////////////////////////

	public function __construct()
	{
		parent::__construct(
			self::ID, $this->get_folder_views());
		UserInputHandlerRegistry::get_instance()->register_handler($this);
	}

	///////////////////////////////////////////////////////////////////////

	public function get_action_map(MediaURL $media_url, &$plugin_cookies)
	{
//		if (!file_exists("/flashdata/plugins/node/bin/node") && PLATFORM_KIND == "android")
//		{
//			$actions[GUI_EVENT_KEY_ENTER] = UserInputHandlerRegistry::create_action($this, "need_install_node");
//			return $actions;
//		}
		return
			array(GUI_EVENT_KEY_ENTER => ActionFactory::open_folder());
	}

////////////////////////////////////////////////////////////////////////////////
	public function handle_user_input(&$user_input, &$plugin_cookies)
	{
		hd_print('PluginScreen: handle_user_input:');
		foreach ($user_input as $key => $value)
		hd_print("  $key => $value");
/*
		if ($user_input->control_id == "need_install_node")
		{
			ControlFactoryExt::add_vgap($defs, 10);
			ControlFactory::add_label($defs, null, 'Для просмотра необходимо установить');
			ControlFactoryExt::add_vgap($defs, -16);
			ControlFactory::add_label($defs, null, 'приложение NODE.');
			ControlFactoryExt::add_vgap($defs, 40);
			$run = UserInputHandlerRegistry::create_action($this, 'run_install_node');
			ControlFactory::add_close_dialog_and_apply_button($btn_defs, $this, null, 'run_install_node', 'Продолжить', 350);
			ControlFactoryExt::add_button_centered($defs, $btn_defs, 800);
			ControlFactory::add_close_dialog_button($btn_defs, 'Отмена', 350);
			ControlFactoryExt::add_button_centered($defs, $btn_defs, 800);
			ControlFactoryExt::add_vgap($defs, 10);

			return
				ActionFactory::show_dialog(null, $defs, false, 800);
		}

		if ($user_input->control_id == 'run_install_node')
		{
			return
				ActionFactory::launch_media_url("plugin_installer://http://plugins.mydune.ru/ddaaff/node/dune_plugin_node.tar.gz:::name=node&need_confirm_replace=0", UserInputHandlerRegistry::create_action($this, 'install_finished'));
		}

		if ($user_input->control_id == 'install_finished')
		{
			$media_url = MediaURL::decode($user_input->parent_media_url);
			$actions = $this->get_action_map($media_url, $plugin_cookies);
			$post_action = ActionFactory::invalidate_folders(array($user_input->parent_media_url), ActionFactory::open_folder());

			return
				ActionFactory::change_behaviour($actions, 0, $post_action);
		}
*/
		if (!isset($user_input->name))
		return null;
	}


	///////////////////////////////////////////////////////////////////////

	public function get_all_folder_items(MediaURL $media_url, &$plugin_cookies)
	{
//var_export($media_url);
		if (is_null($this->category_index))
			$this->fetch_vod_categories();

		$category_list = $this->category_list;

		if (isset($media_url->category_id))
		{
			if (!isset($this->category_index[$media_url->category_id]))
			{
				hd_print("Error: parent category (id: " .
					$media_url->category_id . ") not found.");
				throw new Exception('No parent category found');
			}

			$parent_category = $this->category_index[$media_url->category_id];
			$category_list = $parent_category->get_sub_categories();
		}

		$items = array();

		if (FreeTvConfig::VOD_FAVORITES_SUPPORTED && !isset($media_url->category_id))
		{
			$items[] = array
			(
				PluginRegularFolderItem::media_url => VodFavoritesScreen::get_media_url_str(),
				PluginRegularFolderItem::caption => FreeTvConfig::FAV_MOVIES_CATEGORY_CAPTION,
				PluginRegularFolderItem::view_item_params => array
				(
					ViewItemParams::icon_path => FreeTvConfig::FAV_MOVIES_CATEGORY_ICON_PATH,
					ViewItemParams::item_detailed_icon_path => FreeTvConfig::FAV_MOVIES_CATEGORY_ICON_PATH,
				)
			);
		}

		// SEARCH
		if(!isset($media_url->category_id))
		{
			$items[] = array
			(
				PluginRegularFolderItem::media_url => 'search_screen',
				PluginRegularFolderItem::caption => FreeTvConfig::SEARCH_MOVIES_CATEGORY_CAPTION,
				PluginRegularFolderItem::view_item_params => array
				(
					ViewItemParams::icon_path => FreeTvConfig::SEARCH_MOVIES_CATEGORY_ICON_PATH,
					ViewItemParams::item_caption_color => 14,
					ViewItemParams::item_detailed_icon_path => FreeTvConfig::SEARCH_MOVIES_CATEGORY_ICON_PATH,
				)
			);
		}

		// История
		if(!isset($media_url->category_id))
		{
			$items[] = array
			(
				PluginRegularFolderItem::media_url => 'vod_history_screen',
				PluginRegularFolderItem::caption => FreeTvConfig::HISTORY_MOVIES_CATEGORY_CAPTION,
				PluginRegularFolderItem::view_item_params => array
				(
					ViewItemParams::icon_path => FreeTvConfig::HISTORY_MOVIES_CATEGORY_ICON_PATH,
					ViewItemParams::item_caption_color => 5,
					ViewItemParams::item_detailed_icon_path => FreeTvConfig::HISTORY_MOVIES_CATEGORY_CAPTION,
				)
			);
		}

		foreach ($category_list as $c)
		{
			$is_movie_list = is_null($c->get_sub_categories());
			$media_url_str = $is_movie_list ? VodListScreen::get_media_url_str($c->get_id(), null) : self::get_media_url_str($c->get_id(), null);
			$items[] = array
			(
				PluginRegularFolderItem::media_url => $media_url_str,
				PluginRegularFolderItem::caption => $c->get_caption(),
				PluginRegularFolderItem::view_item_params => array
				(
					ViewItemParams::icon_path => $c->get_icon_path(),
					ViewItemParams::item_detailed_icon_path => $c->get_icon_path()
				)
			);
		}
		return $items;
	}

	///////////////////////////////////////////////////////////////////////

	private function fetch_vod_categories()
	{
	$doc=array(
"Фильмы"=>MEDIA_URL . "/film/?type=films",
"Сериалы"=>MEDIA_URL . "/film/?type=serials",
"Мультфильмы"=>MEDIA_URL . "/film/?type=cartoon",
"Аниме"=>MEDIA_URL . "/film/?type=anime",
);
	$this->category_list = array();
	$this->category_index = array();
	$this->fill_categories($doc, $this->category_list);

	}

	///////////////////////////////////////////////////////////////////////
	private function fill_categories($doc, &$obj_arr)
	{
		foreach ($doc as $title=>$url)
		{
			$cat = new DemoVodCategory(
					strval($url),
					strval($title),
					"plugin_file://icons/folder.png");
			if (!preg_match("|cartoon|", $url) && !preg_match("|anime|", $url))
			{

$genres=array(
"Любой"=>"genre_id=",
"Арт-хаус"=>"genre_id=39",
"Биографический"=>"genre_id=27",
"Блокбастер"=>"genre_id=41",
"Боевик"=>"genre_id=17",
"Вестерн"=>"genre_id=29",
"Военный"=>"genre_id=32",
"Детектив"=>"genre_id=24",
"Детский"=>"genre_id=37",
"Документальный"=>"genre_id=54",
"Драма"=>"genre_id=7",
"Зарубежный"=>"genre_id=10",
"Исторический"=>"genre_id=28",
"Комедия"=>"genre_id=19",
"Короткометражный"=>"genre_id=53",
"Криминал"=>"genre_id=25",
"Мелодрама"=>"genre_id=8",
"Мистический"=>"genre_id=36",
"Музыка"=>"genre_id=109",
"Мюзикл"=>"genre_id=38",
"Полнометражный"=>"genre_id=34",
"Приключения"=>"genre_id=9",
"Путешествия"=>"genre_id=106",
"Развлекательный"=>"genre_id=72",
"Реальное ТВ"=>"genre_id=108",
"Русский"=>"genre_id=22",
"Семейный"=>"genre_id=33",
"Спортивный"=>"genre_id=23",
"Ток-шоу"=>"genre_id=107",
"Триллер"=>"genre_id=13",
"Ужасы"=>"genre_id=26",
"Фантастика"=>"genre_id=11",
"Фэнтези"=>"genre_id=6"
);
			
				
				$gen_arr = array();
					foreach($genres as $k=>$v)
					{
						$genre =
						new DemoVodCategory(
							strval($url . "&" . $v . "&sort=-year"),
							trim(strval($k)),//жанр
							"plugin_file://icons/folder.png");
						array_push($gen_arr, $genre);
					}
				$cat->set_sub_categories($gen_arr);
			}
			$obj_arr[] = $cat;
			$this->category_index[$cat->get_id()] = $cat;
		}
	}

	///////////////////////////////////////////////////////////////////////

	private function get_folder_views()
	{
		return FreeTvConfig::GET_VOD_CATEGORY_LIST_FOLDER_VIEWS();
	}
}

///////////////////////////////////////////////////////////////////////////