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

require_once 'lib/abstract_preloaded_regular_screen.php';

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

class TvChannelListScreen extends AbstractPreloadedRegularScreen implements UserInputHandler
{
	const ID = 'tv_channel_list';

	public static function get_media_url_str($group_id)
	{
		return MediaURL::encode(
			array
			(
				'screen_id' => self::ID,
				'group_id'  => $group_id,
			));
	}

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

	protected $tv;

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

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

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

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

	public function get_sel_item_update_action(&$user_input, &$plugin_cookies)
	{
		$range = HD::create_regular_folder_range($this->get_all_folder_items(MediaURL::decode($user_input->parent_media_url), $plugin_cookies));

		return
			ActionFactory::update_regular_folder($range, false);
	}



	public function get_action_map(MediaURL $media_url, &$plugin_cookies)
	{
		$group_id = $media_url->group_id;
		$group = $this->tv->get_group($group_id);
		$group_name = $group->get_title();
		$actions = array();

		$actions[GUI_EVENT_KEY_ENTER] = ActionFactory::tv_play();
		$actions[GUI_EVENT_KEY_PLAY] = ActionFactory::tv_play();


		if ($this->tv->is_favorites_supported())
		{
			$add_favorite_action = UserInputHandlerRegistry::create_action($this, 'add_favorite');
			$add_favorite_action['caption'] = 'В избранное';
			$popup_menu_action = UserInputHandlerRegistry::create_action($this, 'popup_menu');
//			$open_settings = ActionFactory::open_folder(FreeTvSetupScreen::get_media_url_str());
//			$open_settings['caption'] = 'Настройки';
			if ($group_name != "Корзина")
			$actions[GUI_EVENT_KEY_D_BLUE] = $add_favorite_action;
			$actions[GUI_EVENT_KEY_POPUP_MENU] = $popup_menu_action;
		}
		$actions[GUI_EVENT_KEY_INFO] = UserInputHandlerRegistry::create_action($this, 'info');
		return $actions;
	}


	public function handle_user_input(&$user_input, &$plugin_cookies)
	{
		hd_print('HANDLE_USER_INPUT:');
		foreach ($user_input as $key => $value)
		hd_print("  $key => $value");
		$sel_ndx = $user_input->sel_ndx;

		if ($user_input->control_id == 'info')
		{
			if (!isset($user_input->selected_media_url))
				return null;
			$media_url = MediaURL::decode($user_input->selected_media_url);
			$channel_id = $media_url->channel_id;
			$channels = $this->tv->get_channels();
			$c = $channels->get($channel_id);
			$id = $c->get_id();
			$title = $c->get_title();
			return ActionFactory::show_title_dialog("Channel '$title' (id=$id)");
		}
		else if ($user_input->control_id == 'popup_menu')
		{
			if (!isset($user_input->selected_media_url))
				return null;
			$media_url = MediaURL::decode($user_input->selected_media_url);
			$channel_id = $media_url->channel_id;
			$group_id = $media_url->group_id;
			$group = $this->tv->get_group($group_id);
			$group_name = $group->get_title();
			if ($group_name == "Корзина")
			{
				$caption = 'Восстановить канал';
				$menu_items[] = array(
				GuiMenuItemDef::caption => $caption,
				GuiMenuItemDef::action => UserInputHandlerRegistry::create_action($this, 'restore_single_channel'));

				$caption = 'Восстановить все каналы';
				$menu_items[] = array(
				GuiMenuItemDef::caption => $caption,
				GuiMenuItemDef::action => UserInputHandlerRegistry::create_action($this, 'restore_all_channels'));

				return ActionFactory::show_popup_menu($menu_items);
			}
			$is_favorite = $this->tv->is_favorite_channel_id($channel_id, $plugin_cookies);
			$add_favorite_action = UserInputHandlerRegistry::create_action($this, 'add_favorite');
			$caption = 'Добавить в избранное';
			$menu_items[] = array(
							GuiMenuItemDef::caption => $caption,
							GuiMenuItemDef::action => $add_favorite_action);
			$caption = 'Удалить в корзину';
			$menu_items[] = array(
							GuiMenuItemDef::caption => $caption,
							GuiMenuItemDef::action => UserInputHandlerRegistry::create_action($this, 'move_to_recycle_bin'));
			return ActionFactory::show_popup_menu($menu_items);
		}
		else if ($user_input->control_id == 'add_favorite')
		{
			if (!isset($user_input->selected_media_url))
				return null;
			$media_url = MediaURL::decode($user_input->selected_media_url);
			$channel_id = $media_url->channel_id;
			$is_favorite = $this->tv->is_favorite_channel_id($channel_id, $plugin_cookies);
			if ($is_favorite)
			{
				$this->tv->change_tv_favorites(PLUGIN_FAVORITES_OP_REMOVE, $channel_id, $plugin_cookies);
				return  $this->get_sel_item_update_action($user_input, $plugin_cookies);
			}
			else
			{
				$this->tv->change_tv_favorites(PLUGIN_FAVORITES_OP_ADD, $channel_id, $plugin_cookies);
				return  $this->get_sel_item_update_action($user_input, $plugin_cookies);
			}
		}

/////////////////////////////////////////////
		else if ($user_input->control_id == 'move_to_recycle_bin')
		{
			if (!isset($user_input->selected_media_url))
				return null;
			$media_url = MediaURL::decode($user_input->selected_media_url);
			$channel_id = $media_url->channel_id;
				$exclude_channel_ids = $this->tv->get_exclude_channel_ids($plugin_cookies);
				array_push($exclude_channel_ids, $channel_id);
				$this->tv->set_exclude_channel_ids($plugin_cookies, $exclude_channel_ids);
				$sel_ndx = empty($sel_ndx)? 0 : $user_input->sel_ndx - 1;
				$range = $this->get_folder_range(MediaURL::decode($user_input->parent_media_url), 0, $plugin_cookies);
				return
					ActionFactorySafe::invalidate_folders(array(TvGroupListScreen::get_media_url_str()), ActionFactorySafe::close_and_run(ActionFactorySafe::open_folder($user_input->parent_media_url, null, null, null, ActionFactorySafe::update_regular_folder($range, true, $sel_ndx))));
		}
/////////////////////////////////////////////
		else if ($user_input->control_id == 'restore_all_channels')
		{
			$exclude_channel_ids = array();
			$this->tv->set_exclude_channel_ids($plugin_cookies, $exclude_channel_ids);
			$range = $this->get_folder_range(MediaURL::decode($user_input->parent_media_url), 0, $plugin_cookies);
		return ActionFactorySafe::invalidate_folders(array(TvGroupListScreen::get_media_url_str()), ActionFactorySafe::close_and_run(ActionFactorySafe::open_folder($user_input->parent_media_url, null, null, null, ActionFactorySafe::update_regular_folder($range, true, $sel_ndx))));
		}
/////////////////////////////////////////////
		else if ($user_input->control_id == "restore_single_channel")
		{
				$selected_media_url = MediaURL::decode($user_input->selected_media_url);
				$exclude_channel_ids = $this->tv->get_exclude_channel_ids($plugin_cookies);
				$key = array_search($selected_media_url->channel_id, $exclude_channel_ids);
				if ($key !== false)
					unset($exclude_channel_ids[$key]);
				$num_items = count($exclude_channel_ids);
				$sel_ndx = $user_input->sel_ndx - 1;
				if ($sel_ndx < 0)
					$sel_ndx = 0;
				if ($sel_ndx >= $num_items)
					$sel_ndx = $num_items - 1;
				$this->tv->set_exclude_channel_ids($plugin_cookies, $exclude_channel_ids);
				$range = $this->get_folder_range(MediaURL::decode($user_input->parent_media_url), 0, $plugin_cookies);
		return
			ActionFactorySafe::invalidate_folders(array(TvGroupListScreen::get_media_url_str()), ActionFactorySafe::close_and_run(ActionFactorySafe::open_folder($user_input->parent_media_url, null, null, null, ActionFactorySafe::update_regular_folder($range, true, $sel_ndx))));

		}
		return null;
	}

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

	private function get_regular_folder_item($group, $c, &$plugin_cookies)
	{
	$desc = $c->get_desc();
	$arch = $c->has_archive();
	if ($arch == 0)  $color = 17;
	else $color = 15;
		return array
		(
			PluginRegularFolderItem::media_url =>
				MediaURL::encode(
					array(
						'channel_id' => $c->get_id(),
						'group_id' => $group->get_id())),
			PluginRegularFolderItem::caption => $c->get_title(),
			PluginRegularFolderItem::view_item_params => array
			(
				FolderViewItemParams::icon_path => $c->get_icon_url(),
				FolderViewItemParams::item_detailed_icon_path => $c->get_icon_url(),
				FolderViewItemParams::item_detailed_info => "{$c->get_title()}| ||{$desc}",
				FolderViewItemParams::item_caption_color => $color
			),
			PluginRegularFolderItem::starred =>
				$this->tv->is_favorite_channel_id(
					$c->get_id(), $plugin_cookies),
		);
	}
//////////////////////////////////////////////////////////////////////////////////////////
	public function get_all_folder_items(MediaURL $media_url, &$plugin_cookies)
	{
		$this->tv->folder_entered($media_url, $plugin_cookies);
		$this->tv->ensure_channels_loaded($plugin_cookies);
		$exclude_channel_ids = $this->tv->get_exclude_channel_ids($plugin_cookies);
		$items = array();
		$group = $this->tv->get_group($media_url->group_id);
		$group_name = $group->get_title();
		if ($group_name == "Корзина")
		{
			foreach ($exclude_channel_ids as $channel_id)
			{
				if (is_null($channel = $this->tv->get_channels()->get($channel_id)))
					continue;
				$channels = $this->tv->get_channels();
				$c = $channels->get($channel_id);
				//$id = $c->get_id();
				$title = $c->get_title();
				$icon_url = $c->get_icon_url();
				$desc = $c->get_desc();
				$arch = $c->has_archive();
				if ($arch == 0)  $color = 17;
				else $color = 15;
				$items[] =
				array
				(
				PluginRegularFolderItem::media_url =>
				MediaURL::encode
				(
				array
				(
				'channel_id' => $channel_id,
				'group_id' => $media_url->group_id,
				)
				),
				PluginRegularFolderItem::caption =>$title,
				PluginRegularFolderItem::view_item_params =>
				array
				(
				FolderViewItemParams::icon_path => $icon_url,
				FolderViewItemParams::item_detailed_icon_path => $icon_url,
				FolderViewItemParams::item_detailed_info => "{$c->get_title()}| ||{$desc}",
				FolderViewItemParams::item_caption_color => $color
				),
				);
			}
		return $items;
		}

		else
		{
			foreach ($group->get_channels($plugin_cookies) as $c)
			{
				if (in_array($c->get_id(), $exclude_channel_ids))
					continue;
				$items[] = $this->get_regular_folder_item($group, $c, $plugin_cookies);
			}
		return $items;
		}
	}

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

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