<?php

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

require_once 'lib/folder_view_params.php';
require_once 'lib/abstract_preloaded_regular_screen.php';

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

class TvFavoritesScreen extends AbstractPreloadedRegularScreen
	implements UserInputHandler
{
	const ID = 'tv_favorites';

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

	private static	$browse_mode;
	private	static	$channel_properties_ops;
	private	static	$media_url_str;

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

	private	$plugin;

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

	public static function get_media_url_str($browse_mode = null)
	{
		self::$browse_mode = empty($browse_mode)? TvBrowseModeDefs::normal : $browse_mode;

		return
			MediaURL::encode
			(
				array
				(
					'screen_id' => self::ID,
					'group_id'  => HomeTv::FAV_CHANNELS_GROUP_ID,
				)
			);
	}

	public static function get_active_media_url_str()
	{
		return
			empty(self::$media_url_str)? '' : self::$media_url_str;
	}

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

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

	public function __construct(&$plugin)
	{
		$this->plugin = $plugin;
		parent::__construct(self::ID);
		DefaultDunePlugin::create_screen($this);
		UserInputHandlerRegistry::get_instance()->register_handler($this);
	}

	protected function do_get_folder_views(&$plugin_cookies)
	{
		$views = $this->plugin->channels_screen->get_tv_channels_folder_views($plugin_cookies);
		$views[0][PluginRegularFolderView::view_params][FolderViewParams::background_path] = 'plugin_file://img/bg/main_screen_favorites_list.png';
		$views[1][PluginRegularFolderView::view_params][FolderViewParams::background_path] = 'plugin_file://img/bg/main_screen_favorites_list.png';

		return $views;
	}

	protected function get_update_action($sel_increment, &$user_input, &$plugin_cookies)
	{
		$num_favorites = count($this->plugin->tv->get_fav_channel_ids($plugin_cookies));
		$sel_ndx = $user_input->sel_ndx + $sel_increment;

		if ($sel_ndx < 0)
			$sel_ndx = 0;

		if ($sel_ndx >= $num_favorites)
			$sel_ndx = $num_favorites - 1;

		$post_action = ActionFactorySafe::close_and_run(ActionFactorySafe::open_folder($user_input->parent_media_url, null, null, null, ActionFactorySafe::update_regular_folder(self::create_regular_folder_range($this->get_all_folder_items(MediaURL::decode($user_input->parent_media_url), $plugin_cookies)), true, $sel_ndx)));

		if (NEWGUI_FEAUTURES_AVAILABLE)
		{
			EpfsHandler::update_tv_epfs($plugin_cookies);

			return
				EpfsHandler::invalidate_folders(array(TvGroupsScreen::get_media_url_str()), $post_action);
		}

		return
			ActionFactorySafe::invalidate_folders(array(TvGroupsScreen::get_media_url_str()), $post_action);
	}

	public function get_action_map(MediaURL $media_url, &$plugin_cookies)
	{
		$actions[GUI_EVENT_KEY_SETUP] = UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_SETUP);
		$actions[GUI_EVENT_KEY_MODE] = UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_MODE);

		if ((count($this->plugin->tv->get_fav_channel_ids($plugin_cookies)) <= 0) ||
			(isset($media_url->screen_id) && ($media_url->screen_id == 'empty')))
			return $actions;

		$move_backward_favorite_action = UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_C_YELLOW);
		$move_backward_favorite_action['caption'] = 'Вниз';
		$move_forward_favorite_action = UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_B_GREEN);
		$move_forward_favorite_action['caption'] = 'Вверх';
		$tv_play_action = UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_PLAY);
		$actions[GUI_EVENT_KEY_ENTER] = $tv_play_action;
		$actions[GUI_EVENT_KEY_PLAY] = $tv_play_action;
		$actions[GUI_EVENT_KEY_B_GREEN] = $move_forward_favorite_action;
		$actions[GUI_EVENT_KEY_C_YELLOW] = $move_backward_favorite_action;
		$actions[GUI_EVENT_KEY_POPUP_MENU] = UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_POPUP_MENU);
		$actions[GUI_EVENT_KEY_INFO] = UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_INFO);

		return $actions;
	}

	public function handle_user_input(&$user_input, &$plugin_cookies)
	{
		if (!isset($user_input->selected_media_url))
			return null;

		$selected_media_url = MediaURL::decode($user_input->selected_media_url);
		$channel_id = $selected_media_url->channel_id;
		$sel_ndx = $user_input->sel_ndx;

		switch ($user_input->control_id)
		{
			case GUI_EVENT_KEY_SETUP:
				return
					ActionFactorySafe::open_folder(SettingsScreen::get_media_url_str());//FoldersManager::open_folder(SettingsScreen::get_media_url_str());

			case GUI_EVENT_KEY_MODE:
				$parent_media_url = MediaURL::decode($user_input->parent_media_url);
				$browse_mode = (self::$browse_mode == TvBrowseModeDefs::normal)? TvBrowseModeDefs::full : TvBrowseModeDefs::normal;

				return
					ActionFactorySafe::invalidate_folders(array(self::get_media_url_str($selected_media_url->group_id, $browse_mode), TvGroupsScreen::get_media_url_str($browse_mode)));

			case GUI_EVENT_KEY_PLAY:
				if ($this->plugin->tv->get_channel($channel_id)->is_adult())
					if (($this->plugin->tv->parental->enabled == ControlSwitchDefs::switch_on) && !$this->plugin->tv->parental_passed)
						return
							$this->plugin->tv->get_input_pin_dialog_action($this->plugin->tv);

				return
					UserInputHandlerRegistry::create_action($this->plugin->tv, 'tv_play', array('initial_media_url' => $user_input->selected_media_url));

			case GUI_EVENT_KEY_C_YELLOW:
				if (!isset($user_input->selected_media_url))
					return null;

				return
					$this->plugin->tv->change_tv_favorites(PLUGIN_FAVORITES_OP_MOVE_DOWN, $channel_id, $plugin_cookies);

			case GUI_EVENT_KEY_B_GREEN:
				if (!isset($user_input->selected_media_url))
					return null;

				return
					$this->plugin->tv->change_tv_favorites(PLUGIN_FAVORITES_OP_MOVE_UP, $channel_id, $plugin_cookies);

			case 'remove_favorite':
				if (!isset($user_input->selected_media_url))
					return null;

				return
					$this->plugin->tv->change_tv_favorites(PLUGIN_FAVORITES_OP_REMOVE, $channel_id, $plugin_cookies);

			case 'clear_favorite':
				$empty_array = array();
				$this->plugin->tv->set_fav_channel_ids($empty_array, $plugin_cookies);

				return
					$this->get_update_action(0, $user_input, $plugin_cookies);

			case GUI_EVENT_KEY_INFO:
				return
					$this->plugin->channels_editor->show_info($this);

			case 'edit':
				return
					$this->plugin->channels_editor->show_editor($this);

			case 'move_to_recycle_bin':
				$exclude_channel_ids = $this->plugin->tv->get_exclude_channel_ids();
				array_push($exclude_channel_ids, $channel_id);
				$this->plugin->tv->set_exclude_channel_ids($exclude_channel_ids);
				$sel_ndx = empty($sel_ndx)? 0 : $user_input->sel_ndx - 1;

				return
					$this->get_update_action(0, $user_input, $plugin_cookies);

			case GUI_EVENT_KEY_POPUP_MENU:
				$popup_menu_items[] =
					array
					(
						GuiMenuItemDef::caption => 'Удалить из списка Избранных',
						GuiMenuItemDef::icon_url => 'plugin_file://img/star_rem.png',
						GuiMenuItemDef::action => UserInputHandlerRegistry::create_action($this, 'remove_favorite'),
					);
				$popup_menu_items[] =
					array
					(
						GuiMenuItemDef::caption => 'Удалить в корзину',
						GuiMenuItemDef::icon_url => 'plugin_file://img/bin.png',
						GuiMenuItemDef::action => UserInputHandlerRegistry::create_action($this, 'move_to_recycle_bin'),
					);
				$popup_menu_items[] =
					array
					(
						GuiMenuItemDef::is_separator => true,
					);
				$popup_menu_items[] =
					array
					(
						GuiMenuItemDef::caption => 'Редактировать',
						GuiMenuItemDef::icon_url => 'plugin_file://img/channels_editor.png',
						GuiMenuItemDef::action => UserInputHandlerRegistry::create_action($this, 'edit'),
					);
				$popup_menu_items[] =
					array
					(
						GuiMenuItemDef::is_separator => true,
					);
				$popup_menu_items[] =
					array
					(
						GuiMenuItemDef::caption => 'Очистить список Избранных',
						GuiMenuItemDef::icon_url => 'plugin_file://img/brush.png',
						GuiMenuItemDef::action => UserInputHandlerRegistry::create_action($this, 'clear_favorite'),
					);

				return
					ActionFactorySafe::show_popup_menu($popup_menu_items);
		}
		return null;
	}

	public function get_all_folder_items(MediaURL $media_url, &$plugin_cookies)
	{
		$items = array();
		$this->plugin->tv->folder_entered($media_url, $plugin_cookies);
		$this->plugin->tv->ensure_channels_loaded($plugin_cookies);
		$left_margin = ControlFactoryExt::get_left_margin_str(12);
		$tv_fav_channel_ids = $this->plugin->tv->get_fav_channel_ids($plugin_cookies);
		$tv_exclude_channel_ids = $this->plugin->tv->get_exclude_channel_ids();

		foreach ($tv_fav_channel_ids as $key => $channel_id)
		{
			if (is_null($channel = $this->plugin->tv->channels->get($channel_id)))
			{
				hd_print("Warning: channel '$channel_id' not found and deleted from favorites!");
				continue;
			}

			if (in_array($channel_id, $tv_exclude_channel_ids))
				continue;

			$is_corrupted = is_null($this->plugin->tv->get_tv_playback_url($channel_id, 0, RET_LIVE_TEMPLATE_URL));

			if ((self::$browse_mode == TvBrowseModeDefs::normal) && $is_corrupted)
				continue;

			$item_idx = count($items);
			$title = $channel->get_title();
			$icon_url = $channel->get_icon_url();
			$num_length = strlen($channel->get_number());
			$items[] =
				array
				(
					PluginRegularFolderItem::media_url =>
						MediaURL::encode
						(
							array
							(
								'group_id' => HomeTv::FAV_CHANNELS_GROUP_ID,
								'channel_id' => $channel->get_id(),
							)
						),
					PluginRegularFolderItem::caption => $channel->get_number() . $left_margin . $title,
					PluginRegularFolderItem::view_item_params =>
						array
						(
							FolderViewItemParams::item_caption_dx => (($num_length > 2)? 40 : (($num_length > 1)? 60 : 83)) - 2,
							FolderViewItemParams::icon_path => $icon_url,
							FolderViewItemParams::item_detailed_icon_path => $icon_url,
							FolderViewItemParams::item_detailed_info => "|| ||{$title}| ||{$channel->get_desc()}",
							FolderViewItemParams::item_detailed_icon_width => 460,
							FolderViewItemParams::item_detailed_icon_height => 260,
							FolderViewItemParams::item_badge_icon_path => 'plugin_file://img/channel_badge.png',
						),
					PluginRegularFolderItem::starred => false,
				);

			if ($is_corrupted)
				$items[$item_idx][PluginRegularFolderItem::view_item_params][ViewItemParams::item_caption_color] = DEF_LABEL_TEXT_COLOR_DIMGRAY;
		}

		if (empty($items))
		{
			$items[] =
				array
				(
					PluginRegularFolderItem::media_url => 'empty',
					PluginRegularFolderItem::caption => '(пусто)',
					PluginRegularFolderItem::view_item_params =>
						array
						(
							FolderViewItemParams::item_caption_color => DEF_LABEL_TEXT_COLOR_GAINSBORO,
							FolderViewItemParams::item_detailed_info => '||',
						),
				);
		}

		return $items;
	}

	public function get_archive(MediaURL $media_url, &$plugin_cookies)
	{
		return
			$this->plugin->tv->get_archive($media_url, $plugin_cookies);
	}

	public function get_folder_view(MediaURL $media_url, &$plugin_cookies)
	{
		$this->ensure_folder_views($plugin_cookies);
		$idx = $this->get_folder_view_index($plugin_cookies);
		$folder_view = $this->folder_views[$idx];
		$folder_view[PluginRegularFolderView::initial_range] = $this->get_folder_range($media_url, 0, $plugin_cookies);
		$folder_media_url = MediaURL::decode($folder_view[PluginRegularFolderView::initial_range][PluginRegularFolderRange::items][0][PluginRegularFolderItem::media_url]);
		$folder_view[PluginRegularFolderView::actions] = $this->get_action_map($folder_media_url, $plugin_cookies);

		if (self::$browse_mode == TvBrowseModeDefs::full)
			$folder_view[PluginFolderView::data][PluginRegularFolderView::view_params][FolderViewParams::extra_content_objects] = 'label{x=1330}{y=-52}{color=' . DEF_LABEL_TEXT_COLOR_YELLOW . '}{text=Экспертный режим}';

		if (isset($folder_media_url->screen_id) && ($folder_media_url->screen_id == 'empty'))
			$folder_view[PluginRegularFolderView::view_params][ViewParams::paint_icon_selection_box] = false;

		$result =
			array
			(
				PluginFolderView::multiple_views_supported  => (count($this->folder_views) > 1 ? 1 : 0),
				PluginFolderView::archive                   => is_null($archive = $this->get_archive($media_url, $plugin_cookies)) ? null : $archive->get_archive_def(),
				PluginFolderView::view_kind                 => PLUGIN_FOLDER_VIEW_REGULAR,
				PluginFolderView::data                      => $folder_view
			);

		return $result;
	}
}

?>
