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

#require_once 'lib/tv/tv_group_list_screen.php';
require_once 'lib/abstract_preloaded_regular_screen.php';
require_once 'lib/abstract_controls_screen.php';

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

class MyPlugIN_TvGroupListScreen extends AbstractPreloadedRegularScreen implements UserInputHandler
{
    const ID = 'tv_group_list';
	
	private $session = NULL;
	protected $tv;
	public function __construct($tv, $folder_views, $session)
    {
        parent::__construct(self::ID, $folder_views);
		$this->session = $session;
		$this->tv = $tv;
        UserInputHandlerRegistry::get_instance()->register_handler($this);
    }
	public function get_handler_id()
	{
		return self::ID;
	}
    ///////////////////////////////////////////////////////////////////////
    public static function get_media_url_str()
    {
        return MediaURL::encode(
            array
            (
                'screen_id' => self::ID,
            ));
    }
    
    public function _whats_new_dialog()
    {
        $cur_version = VERSION_MAJOR . '.' . VERSION_MINOR . '.' . VERSION_SUBMINOR;
        
        $plugin_dir  = DuneSystem::$properties['install_dir_path'];
        $plugin_name = basename($plugin_dir);
        
        $doc = HD::http_get_document("http://igores.ru/dune/update/$plugin_name/update_info.xml");
        $xml = simplexml_load_string($doc);
        if ($xml === false)
            return null;

        if ($xml->getName() !== 'info')
            return null;

        $text = false;
        foreach ($xml->children() as $version)
        {
            if ($version->getName() != 'version')
                continue;
                
            if ($version->number == $cur_version)
            {
                $text = $version->whats_new;
                break;
            }
        }
        
        if (!$text)
            return null;
            
        $defs = array();
        $texts = explode("\\n", $text);
        $texts = array_values($texts);
        foreach($texts as $text)
        {
            ControlFactory::add_label($defs, "", $text);
        }
        ControlFactory::add_close_dialog_button($defs, 'OK', 150);

        return ActionFactory::show_dialog('Изменения в версии ' . $cur_version, $defs);
    }
    
    ///////////////////////////////////////////////////////////////////////
	public function get_action_map(MediaURL $media_url, &$plugin_cookies)
	{
		//////////////////////////////////igores////////////////////////////////////////////
		$version = VERSION_MAJOR . '.' . VERSION_MINOR . '.' . VERSION_SUBMINOR;
		$add_action = UserInputHandlerRegistry::create_action($this, 'whats_new');
		$add_action['caption'] = 'Изменения в ' . $version;
		
		$setup_view = UserInputHandlerRegistry::create_action($this, 'do_setup_menu');
		$setup_view['caption'] = 'Настройки плагина';
		
		$popup_menu_action = UserInputHandlerRegistry::create_action($this, 'popup_menu');
		//////////////////////////////////////////////////////////////////////////////
		return array
		(
		GUI_EVENT_KEY_ENTER => ActionFactory::open_folder(),
		GUI_EVENT_KEY_PLAY  => ActionFactory::tv_play(),
//		GUI_EVENT_KEY_C_YELLOW => $add_action,
		GUI_EVENT_KEY_D_BLUE => $setup_view,
		GUI_EVENT_KEY_SETUP => $setup_view,
		GUI_EVENT_KEY_POPUP_MENU => $popup_menu_action
		);
	}
	////////////////////////////////////////////////////////////////////////
    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);
        $items = array();
        foreach ($this->tv->get_groups() as $group)
        {
            $media_url = $group->is_favorite_channels() ? TvFavoritesScreen::get_media_url_str() : MyPlugINTvChannelListScreen::get_media_url_str($group->get_id());
				#$test = json_decode(MyPlugINTvChannelListScreen::get_media_url_str($group->get_id()));
				$items[] = array
				(
					PluginRegularFolderItem::media_url => $media_url,
					PluginRegularFolderItem::caption => $group->get_title(),
					PluginRegularFolderItem::view_item_params => array
					(
						ViewItemParams::icon_path => $group->get_icon_url(),
						ViewItemParams::item_detailed_icon_path => $group->get_icon_url()
					)
				);
        }

        $this->tv->add_special_groups($items);

        return $items;
    }
	///////////////////////////////////////////////////////////////////////
	protected function add_close_dialog_button(&$defs,
        $caption, $width)
    {
        $params = array('button_caption_centered' => 1);
        ControlFactory::add_close_dialog_button($defs,
            $caption, $width, $params);
    }
	protected function add_close_dialog_and_apply_button(&$defs,
        $name, $caption, $width)
    {
        $params = array('button_caption_centered' => 1);
        ControlFactory::add_close_dialog_and_apply_button($defs,
            $this, null,
            $name, $caption, $width, $params);
    }
	private function restore_hide_categories_defs($plugin_cookies)
	{
		$plugin_cookies->hide_category_items = '';
		$defs = array();
		ControlFactory::add_label($defs, "", "Весь список скрытых категорий будет восстановлен!!!");
		ControlFactory::add_label($defs, "", "Для применения изменений необходима перезагрузка плеера! ");
		ControlFactory::add_label($defs, "", "Перезагрузить плеер сейчас?");
		$this->add_close_dialog_and_apply_button($defs, 'restart_restore', 'Да', 250);
		$this->add_close_dialog_button($defs, 'Нет', 250);
		return $defs;
	}
	private function make_hide_category_defs($category_id, $title, &$plugin_cookies)
	{
		$hide_category_items = isset($plugin_cookies->hide_category_items) ? $plugin_cookies->hide_category_items : '';
		if (!ListUtil::is_in_list($hide_category_items, $category_id))
		{
			$plugin_cookies->hide_category_items = ListUtil::add_item($hide_category_items, $category_id);		
			$defs = array();
			ControlFactory::add_label($defs, "", "Категория " . "«" . $title . "»" . " с ID " . "«" . $category_id . "»" . " будет скрыта после перезагрузки плеера!");
			ControlFactory::add_label($defs, "", "Для применения изменений необходима перезагрузка плеера! ");
			ControlFactory::add_label($defs, "", "Вы можете продолжать скрывать другие категории. ");
			ControlFactory::add_label($defs, "", "Перезагрузить плеер сейчас?");
			$this->add_close_dialog_button($defs, 'Позже', 300);
			$this->add_close_dialog_and_apply_button($defs, 'restart_hide', 'Сейчас', 300);
			return $defs;
		}
	}
	private function restore_only_category_defs($category_id, $title, &$plugin_cookies)
    {			
			$defs = array();
			ControlFactory::add_label($defs, "", "Категория " . "«" . $title . "»" . " с ID " . "«" . $category_id . "»" . " будет восстановлена после перезагрузки плеера!");
			ControlFactory::add_label($defs, "", "Для применения изменений необходима перезагрузка плеера! ");
			ControlFactory::add_label($defs, "", "Вы можете продолжать восстанавливать другие категории. ");
			ControlFactory::add_label($defs, "", "Перезагрузить плеер сейчас?");
			$this->add_close_dialog_button($defs,
				'Позже', 300);
			$this->add_close_dialog_and_apply_button($defs,
				'restart_hide', 'Сейчас', 300);
			return $defs;
    }
	#############################NEW###############################################
	public function handle_user_input(&$user_input, &$plugin_cookies)
	{
		$hided_categories = isset($plugin_cookies->hided_categories) ? $plugin_cookies->hided_categories : 'no';
		$hide_category_items = isset($plugin_cookies->hide_category_items) ? $plugin_cookies->hide_category_items : '';		
		foreach ($user_input as $key => $value)
			hd_print("user_input  $key => $value");
		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);
			$group_id = $media_url->group_id;
			$hide_category_action = UserInputHandlerRegistry::create_action($this, 'hide_category');
			$hide_category_caption = 'Скрыть категорию';		
			$restore_category_action = UserInputHandlerRegistry::create_action($this, 'restore_categories_dialog');
			$restore_category_caption = 'Восстановить все скрытые категории';		
			$restore_category_n_action = UserInputHandlerRegistry::create_action($this, 'restore_categories_n_dialog');
			$restore_category_n_caption = 'Восстановить отдельные скрытые категории';
			$menu_items[] = array(
			GuiMenuItemDef::caption => $hide_category_caption,
			GuiMenuItemDef::action => $hide_category_action,
			GuiMenuItemDef::icon_url => 'plugin_file://icons/small/hide_channel.aai');
			if($hide_category_items <> '')
			{
				$menu_items[] = array(
				GuiMenuItemDef::caption => $restore_category_caption,
				GuiMenuItemDef::action => $restore_category_action,
				GuiMenuItemDef::icon_url => 'plugin_file://icons/small/restore_all.aai');		
				$menu_items[] = array(
				GuiMenuItemDef::caption => $restore_category_n_caption,
				GuiMenuItemDef::action => $restore_category_n_action,
				GuiMenuItemDef::icon_url => 'plugin_file://icons/small/restore_all.aai');
			}
			$menu_items [] =  array(
			GuiMenuItemDef::is_separator => true,);		
			return ActionFactory::show_popup_menu($menu_items);
		}
		#############################################################################
		else if ($user_input->control_id == 'hide_category')
		{
			if (!isset($user_input->selected_media_url))
				return null;		
			$media_url = MediaURL::decode($user_input->selected_media_url);
			$group_id = $media_url->group_id;
			$cat_title = $this->categ_id($group_id);
			$hide_category_items = isset($plugin_cookies->hide_category_items) ? $plugin_cookies->hide_category_items : '';
			if (!ListUtil::is_in_list($hide_category_items, $group_id))
			{
				if($group_id == '__all_channels')
				{
					return ActionFactory::show_title_dialog("НЕЛЬЗЯ СКРЫТЬ КАТЕГОРИЮ «ВСЕ КАНАЛЫ»!!!");
				}
				elseif($group_id == '')
				{
					return ActionFactory::show_title_dialog("НЕЛЬЗЯ СКРЫТЬ «ИЗБРАННОЕ»!!!");
				}
				$defs = $this->make_hide_category_defs($group_id, $cat_title, &$plugin_cookies);
				return  ActionFactory::show_dialog("Внимание!!!", $defs, true);
				break;
			}
		}
		else if ($user_input->control_id == 'restore_categories_dialog')
		{
			$defs = $this->restore_hide_categories_defs($plugin_cookies);
			return  ActionFactory::show_dialog
			("Внимание!!!",
			$defs,
			true);
		}
		else if ($user_input->control_id == 'restore_categories_n_dialog')
		{
			$defs = $this->restore_hide_categories_n_defs($plugin_cookies);
			return  ActionFactory::show_dialog
			("Восстановить отдельные категории?",
			$defs,
			true);
		}
		else if ($user_input->control_id == 'view_hide_categories_action')
		{
			$plugin_cookies->hided_categories = 'yes';
			$perform_new_action = UserInputHandlerRegistry::create_action(
			$this, 'reset_controls');
			return ActionFactory::invalidate_folders(array('tv_group_list'), $perform_new_action);
		}
		else if ($user_input->control_id == 'hide_hide_categories_action')
		{
			$plugin_cookies->hided_categories = 'no';
			$perform_new_action = UserInputHandlerRegistry::create_action(
			$this, 'reset_controls');
			return ActionFactory::invalidate_folders(array('tv_group_list'), $perform_new_action);
		}
		else if ($user_input->control_id == 'restore_categories')
		{
			$plugin_cookies->hide_category_items = '';
			$perform_new_action = UserInputHandlerRegistry::create_action(
			$this, 'reset_controls');
			return ActionFactory::invalidate_folders(array('tv_group_list'), $perform_new_action);
		}
		else if ($user_input->control_id === 'restart_hide')
		{		
			$perform_new_action = UserInputHandlerRegistry::create_action(	$this, 'reset_controls');
			ActionFactory::invalidate_folders(array('tv_group_list'), $perform_new_action);
			usleep(500000);
			if (file_exists('/system/dunehd/init'))
				shell_exec("killall com.dunehd.shell");
			else
				shell_exec('killall shell');
		}
		else if ($user_input->control_id === 'restart_restore')
		{		
			$perform_new_action = UserInputHandlerRegistry::create_action($this, 'reset_controls');
			ActionFactory::invalidate_folders(array('tv_group_list'), $perform_new_action);
			usleep(500000);
			if (file_exists('/system/dunehd/init'))
				shell_exec("killall com.dunehd.shell");
			else
				shell_exec('killall shell');
		}
		else if ($user_input->control_id == 'restore_categ')
		{		
			if ($user_input->cat)
				$cat = $user_input->cat;
			$cat_title = $this->categ_id($cat);
			$hide_category_items = isset($plugin_cookies->hide_category_items) ? ListUtil::del_item($plugin_cookies->hide_category_items, $cat) : '';
			$plugin_cookies->hide_category_items = $hide_category_items;
			#hd_print("OOOOOPPPPSSS--------->$hide_category_items");
			$defs = $this->restore_only_category_defs($cat, $cat_title, &$plugin_cookies);
			return  ActionFactory::show_dialog("Внимание!!!", $defs, true);
			break;		
		}
		if($user_input->control_id == 'do_setup_menu')
		{
			return ActionFactory::open_folder('setup');
		}
		if($user_input->control_id == 'whats_new')
		{
			return $this->_whats_new_dialog();
		}
		return null;	
	}

	private function categ_id($cat)
	{
return DuneSystem::$properties["cats_prostotv"][$cat];
/*
		$categories = array (
		intval(5)  => 'Познавательные',
		intval(6)        => 'Развлекательные',
		intval(19) => 'Для детей',
		intval(2)        => 'Русские',
		intval(23) => 'Спорт',
		intval(24)       => 'Немецкие',
		intval(1)  => 'Украинские',
		intval(21)       => 'Мужские',
		intval(8)  => 'Музыка',
		intval(20)       => 'Кино',
		intval(22) => 'Для взрослых',
		intval(4)        => 'Информационные',
		intval(3)  => 'Региональные',
		'__all_channels' => 'Все каналы'
		);
		
		foreach ($categories as $key => $value)
		{
			$cat = str_replace($key, $value, $cat);
		}
		return $cat;
*/
	}

	###################
	private function restore_hide_categories_n_defs(&$plugin_cookies)
    {
		$hide_category_items = isset($plugin_cookies->hide_category_items) ? $plugin_cookies->hide_category_items : '';
		$items = $plugin_cookies->hide_category_items;
		$defs = array();
		if(preg_match("/|/", $items, $mat))
		{
			$cat = array();
			$tmp = explode('|', $items);
			foreach($tmp as $s)
			{
				$categ = $this->categ_id(intval($s));
				$add_params ['cat'] = $s;
				ControlFactory::add_button($defs, $this, $add_params, 'restore_categ', '', "Восстановить категорию «" .  $categ . '»', 900);			
			}
		}
		else
		{
			$s = $items;
			$categ = $this->categ_id(intval($s));
			$add_params ['cat'] = $s;
			ControlFactory::add_button($defs, $this, $add_params, 'restore_categ', '', "Восстановить категорию «" .  $categ . '»', 900);
		}
		
			ControlFactory::add_label($defs, '', '   ');
			$this->add_close_dialog_button($defs,'Закрыть', 200);
			
			return $defs;
	}
}

///////////////////////////////////////////////////////////////////////////
?>
