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

require_once 'lib/abstract_regular_screen.php';

class VodListScreen extends AbstractRegularScreen implements UserInputHandler
{
	const ID = 'vod_list';

	private $vod;
	private $folder_views;
	private $show_rus_only;
	private $folder_view_index_attr_name;

	public $total = array();
	public $isOpened = false;
	public $m_feed = array();

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

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

		if ($name == true)
			$arr['name'] = $name;

		return MediaURL::encode($arr);
	}

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

	protected function get_short_movie_range(MediaURL $media_url, $from_ndx, &$plugin_cookies)
	{
		$movies = array();
		if ($this->isOpened)
		{
			$this->isOpened = false;
			$this->m_feed = array();
		}

		if ($media_url->category_id == 'search')
		{
			$movies = DemoTv::getSearchList($media_url->genre_id, $this->m_feed);
			if(!count($movies))
				return new ShortMovieRange(0, 0);
		}

		else
		{
			$movies = DemoTv::getVideoList($media_url->category_id, $media_url->genre_id, $this->m_feed);
			if(!count($movies))
				return new ShortMovieRange(0, 0);
		}

		if (!array_key_exists($media_url->category_id."_".$media_url->genre_id, $this->total))
			$this->total[$media_url->category_id."_".$media_url->genre_id] = 0;

		$this->total[$media_url->category_id."_".$media_url->genre_id] += count($movies);
		return new ShortMovieRange($from_ndx, $this->total[$media_url->category_id."_".$media_url->genre_id], $movies);
	}

	protected function get_vod_list_folder_views(&$plugin_cookies)
	{
		return $this->vod->get_vod_list_folder_views($this->bg_index);

	}

	protected function get_folder_view_index(&$plugin_cookies)
	{
		if (!isset($plugin_cookies->{$this->folder_view_index_attr_name}))
			return 0;

		$idx = $plugin_cookies->{$this->folder_view_index_attr_name};

		$cnt = count($this->folder_views);

		if ($idx < 0)
			$idx = 0;
		else if ($idx >= $cnt)
			$idx = $cnt - 1;

		return intval($idx);
	}

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

	public function __construct(Vod $vod)
	{
		$this->vod = $vod;
		$this->m_feed = array();
		$this->total = array();
		$this->show_rus_only = 0;
		$this->folder_view_index_attr_name = "screen." . self::ID . ".view_idx";

		parent::__construct(self::ID, null);
		UserInputHandlerRegistry::get_instance()->register_handler($this);
	}

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

	public function get_action_map(MediaURL $media_url, &$plugin_cookies)
	{
		$actions = array();

		if ($this->vod->is_movie_page_supported())
			$actions[GUI_EVENT_KEY_ENTER] = ActionFactory::open_folder();
		else
			$actions[GUI_EVENT_KEY_ENTER] = ActionFactory::vod_play();

		$add_action = UserInputHandlerRegistry::create_action($this, 'search');
		$add_action['caption'] = 'Поиск';
		$actions[GUI_EVENT_KEY_C_YELLOW] = $add_action;

		$add_action = UserInputHandlerRegistry::create_action($this, 'add_favorite');
		$add_action['caption'] = 'В Избранное';
		$actions[GUI_EVENT_KEY_D_BLUE] = $add_action;


		if (preg_match("|type=films|", $media_url->category_id) || preg_match("|type=serials|", $media_url->category_id))
		{
			$add_action = UserInputHandlerRegistry::create_action($this, 'sort_page');
			$add_action['caption'] = "Все/RUS";
			$actions[GUI_EVENT_KEY_B_GREEN] = $add_action;
		}
		return $actions;
	}

	public function get_handler_id()
	{ return self::ID; }


	public function handle_user_input(&$user_input, &$plugin_cookies)
	{
		if ($user_input->control_id == 'sort_page')
		{
			$this->show_rus_only = ($this->show_rus_only > 0)? 0 : 1;
			$media_url = MediaURL::decode($user_input->parent_media_url);
			$post_action = ActionFactory::update_regular_folder($this->get_folder_range($media_url, 0, $plugin_cookies), true, 0);
			return
				ActionFactory::invalidate_folders(array($user_input->parent_media_url),$post_action);
		}
		else if ($user_input->control_id == 'search')
		{
			if (!isset($user_input->selected_media_url))
				return null;
			$media_url = MediaURL::decode($user_input->selected_media_url);
			$defs = array();
			ControlFactory::add_text_field($defs, $this, $add_params=null, 'do_new_search', '', $media_url->name, 0, 0, 1, 1, 1300,0,1);
			ControlFactory::add_vgap($defs, 500);
			return ActionFactory::show_dialog('Поиск', $defs, true);
		}
		else if ($user_input->control_id == 'do_new_search')
		{
			$do_search = UserInputHandlerRegistry::create_action($this, 'do_search');
			return ActionFactory::close_dialog_and_run($do_search);
		}
		else if ($user_input->control_id == 'do_search')
		{
			$media_url = MediaURL::decode($user_input->selected_media_url);
			HD::save_item('search_item', $user_input->do_new_search);
			$search_items = HD::get_items('search_items');
			$k = array_search($user_input->do_new_search, $search_items);

			if ($k !== false)
				unset($search_items[$k]);

			array_unshift($search_items, $user_input->do_new_search);
			HD::save_items('search_items', $search_items);
			$action = ActionFactory::open_folder(VodListScreen::get_media_url_str('search', $user_input->do_new_search), "Поиск: ".$user_input->do_new_search);
			return ActionFactory::invalidate_folders(array('search_screen'),$action);
		}
		else if ($user_input->control_id == 'add_favorite')
		{
			if (!isset($user_input->selected_media_url))
				return null;
			$this->vod->ensure_favorites_loaded($plugin_cookies);
			$is_favorite = $this->vod->is_favorite_movie_id($user_input->selected_media_url);
			if ($is_favorite)
			{
				$this->vod->remove_favorite_movie($user_input->selected_media_url, $plugin_cookies);
				return ActionFactory::show_title_dialog('Удалено из Избранного');
			}
			else
			{
				$this->vod->add_favorite_movie($user_input->selected_media_url, $plugin_cookies);
				return ActionFactory::show_title_dialog('Добавленно в Избранное');
			}
		}

		return null;
	}

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

	public function get_folder_range(MediaURL $media_url, $from_ndx, &$plugin_cookies)
	{
		if ($this->show_rus_only)
			//$media_url->category_id = $media_url->category_id . "_rus_su";
			$media_url->category_id = $media_url->category_id . "&country_id=5";
		$movie_range = $this->get_short_movie_range($media_url, $from_ndx, $plugin_cookies);
		$total = intval($movie_range->total);

		if ($total <= 0)
			return HD::create_regular_folder_range(array());

		$items = array();

		foreach ($movie_range->short_movies as $movie)
		{
			$items[] = array
			(
				PluginRegularFolderItem::media_url =>
				VodMovieScreen::get_media_url_str($movie->id, $movie->name, $movie->poster_url, $movie->info),
				PluginRegularFolderItem::caption => $movie->name,
				PluginRegularFolderItem::view_item_params => array
				(
			ViewItemParams::icon_path => $movie->poster_url,
			ViewItemParams::item_detailed_info => $movie->info,
			ViewItemParams::item_caption_color => 15,
				)
			);
			$this->vod->set_cached_short_movie(new ShortMovie($movie->id, $movie->name, $movie->poster_url));
		}

		return HD::create_regular_folder_range($items, $movie_range->from_ndx, $total, true);
	}

	public function get_next_folder_view(MediaURL $media_url, &$plugin_cookies)
	{
		$idx = $this->get_folder_view_index($plugin_cookies);

		++$idx;

		if ($idx >= count($this->folder_views))
			$idx = 0;

		$plugin_cookies->{$this->folder_view_index_attr_name} = $idx;

		return $this->get_folder_view($media_url, $plugin_cookies);
	}

	public function get_folder_view(MediaURL $media_url, &$plugin_cookies)
	{
		if (preg_match("|/animation|", $media_url->category_id) || preg_match("|/tv|", $media_url->category_id) || $media_url->category_id == "search")
			$this->show_rus_only = 0;
		$this->isOpened = true;
		$this->total = array();
		$this->m_feed = array();
		$this->vod->clear_movie_cache();
		$this->vod->folder_entered($media_url, $plugin_cookies);
		$this->folder_views = $this->vod->get_vod_list_folder_views($this->show_rus_only);
		$idx = $this->get_folder_view_index($plugin_cookies);
		$folder_view = $this->folder_views[$idx];
		$folder_view[PluginRegularFolderView::actions] = $this->get_action_map($media_url, $plugin_cookies);
		$folder_view[PluginRegularFolderView::initial_range] = $this->get_folder_range($media_url, 0, $plugin_cookies);
		$archive = $this->get_archive($media_url);
		$archive_def = is_null($archive) ? null : $archive->get_archive_def();

		return
			array
			(
				PluginFolderView::multiple_views_supported  => (count($this->folder_views) > 1 ? 1 : 0),
				PluginFolderView::archive                   => $archive_def,
				PluginFolderView::view_kind                 => PLUGIN_FOLDER_VIEW_REGULAR,
				PluginFolderView::data                      => $folder_view
			);
	}

	public function get_archive(MediaURL $media_url)
	{
		return $this->vod->get_archive($media_url);
	}

}

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