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

#require_once 'lib/abstract_preloaded_regular_screen.php';

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

class MyPlugINTvChannelListScreen extends TvChannelListScreen
    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;
    private $session;
    ///////////////////////////////////////////////////////////////////////

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

    ///////////////////////////////////////////////////////////////////////
	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_channels_defs($plugin_cookies)
    {
	$plugin_cookies->hide_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 view_hide_channels_defs()
    {
        $defs = array();
        ControlFactory::add_label($defs, "", "Скрытые каналы появятся в списке при повторном входе в категорию!");
		ControlFactory::add_label($defs, "", "Не забудьте отключить!");
		ControlFactory::add_label($defs, "", "Хотите продолжить?");
		$this->add_close_dialog_and_apply_button($defs,
            'view_hide_channel_action', 'Да', 250);
        $this->add_close_dialog_button($defs,
            'Нет', 250);
        return $defs;
    }
	private function hide_hide_channels_defs()
    {
        $defs = array();
        ControlFactory::add_label($defs, "", "Cкрытые каналы будут вновь спрятаны!!!");
		ControlFactory::add_label($defs, "", "Хотите продолжить?");
		$this->add_close_dialog_and_apply_button($defs,
            'hide_hide_channel_action', 'Да', 250);
        $this->add_close_dialog_button($defs,
            'Нет', 250);
        return $defs;
    }
	private function make_hide_channels_defs($channel_id, $title, &$plugin_cookies)
    {
		$hide_items = isset($plugin_cookies->hide_items) ? $plugin_cookies->hide_items : '';
			if (!ListUtil::is_in_list($hide_items, $channel_id))
            {
            $plugin_cookies->hide_items = ListUtil::add_item($hide_items,$channel_id);
					
			}
        $defs = array();
        ControlFactory::add_label($defs, "", "Канал " . "«" . $title . "»" . " с ID " . "«" . $channel_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;
    }

    public function get_action_map(MediaURL $media_url, &$plugin_cookies)
    {
        $actions = array();
        #$actions[GUI_EVENT_KEY_ENTER] = ActionFactory::tv_play();
        #$actions[GUI_EVENT_KEY_PLAY] = ActionFactory::tv_play();
        $open_folder_action = UserInputHandlerRegistry::create_action(
                $this, 'play_stream');
        $actions[GUI_EVENT_KEY_ENTER] = $open_folder_action;
		$actions[GUI_EVENT_KEY_PLAY] = $open_folder_action;
       

        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');

            $actions[GUI_EVENT_KEY_D_BLUE] = $add_favorite_action;
			$actions[GUI_EVENT_KEY_POPUP_MENU] = $popup_menu_action;
        }
		
		
			/* $add_pvr = UserInputHandlerRegistry::create_action(
                    $this, 'pvr');
            $add_pvr['caption'] = 'управление записью EPG';
			$actions[GUI_EVENT_KEY_B_GREEN] = $add_pvr; */
			 
        $actions[GUI_EVENT_KEY_INFO] =
           UserInputHandlerRegistry::create_action(
               $this, 'info');
        $actions[GUI_EVENT_KEY_CLEAR] =
            UserInputHandlerRegistry::create_action(
                $this, 'hide_channel');
        return $actions;
    }


    private function get_sel_item_update_action(&$user_input, &$plugin_cookies,$sel_increment=null)
    {
	$parent_media_url = MediaURL::decode($user_input->parent_media_url);
	$sel_ndx = $user_input->sel_ndx;
	if ($sel_ndx < 0)
		$sel_ndx = 0;
	$group = $this->tv->get_group($parent_media_url->group_id);
	$channels = $group->get_channels($plugin_cookies);
	$items[] = $this->get_regular_folder_item($group, $channels->get_by_ndx($sel_ndx), $plugin_cookies);
	$range = HD::create_regular_folder_range($items, $sel_ndx, $channels->size());
	
	return ActionFactory::update_regular_folder($range, false);
    }
    
    public function handle_user_input(&$user_input, &$plugin_cookies)
    {
        hd_print('Tv favorites: handle_user_input:');
		$hided_channels = isset($plugin_cookies->hided_channels) ? $plugin_cookies->hided_channels : 'no';
		$hide_items = isset($plugin_cookies->hide_items) ? $plugin_cookies->hide_items : '';
        foreach ($user_input as $key => $value)
            hd_print("  $key => $value");
        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("Канал: $title - (ID = $id)");
        }
		/* elseif ($user_input->control_id == 'pvr')
        {
		    if (!isset($user_input->selected_media_url))
                return null;
            $media_url = MediaURL::decode($user_input->selected_media_url);
            $channel_id = $media_url->channel_id;
			///////////////////////////////////////////////////////////////////////////////////

			for($i=0; $i<7; $i++) {
			$date = strtotime("$i day");
			$select_day_action =
                UserInputHandlerRegistry::create_action(
                    $this, "select_day_".$date.'|'.$channel_id);

	    $menu_items[] = array(
                GuiMenuItemDef::caption => date('d,m,Y', strtotime("$i day")),
                GuiMenuItemDef::action => $select_day_action);
	    } 

            return ActionFactory::show_popup_menu($menu_items);
		}
		elseif (substr($user_input->control_id, 0, 11) == 'select_day_')
        {
		    if (!isset($user_input->selected_media_url))
                return null;
			$explode = explode('|', substr($user_input->control_id, 11));	
			$epg = $this->session->get_stalker_epg($explode[0], $explode[1], 0, &$plugin_cookies);
			///////////////////////////////////////////////////////////////////////////////////
			unset($epg->results[0]);
			foreach ($epg->results as $epg_item) {
			
			$select_source_action =
                UserInputHandlerRegistry::create_action(
                    $this, "select_source_".strval($epg_item->id));

	    $menu_items[] = array(
                GuiMenuItemDef::caption => date('H', intval($epg_item->start)).':'.date('i', intval($epg_item->start)).'-'.strval($epg_item->name),
                GuiMenuItemDef::action => $select_source_action);
	    } 

            return ActionFactory::show_popup_menu($menu_items);
		}
		elseif (substr($user_input->control_id, 0, 14) == 'select_source_')
        {
            if (!isset($user_input->selected_media_url))
                return null;

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

	    $src = substr($user_input->control_id, 14);	     
		

	    return ActionFactory::show_title_dialog("Выбрана запись: $src");
        } */
        elseif ($user_input->control_id == 'play_stream'){
		#$this->session->isogged_srv();
		hd_print("PLAY__STREAM");
		return ActionFactory::tv_play();
		}
	
        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;
			$bgr_rs = DuneSystem::$properties['tmp_dir_path'] . '/background_rec_stop';
			if (file_exists($bgr_rs)) {
			$name = trim(file_get_contents($bgr_rs));
			$dd = "/tmp/".$name."_tvclubrec.sh";
			if (!file_exists($dd))
				unlink($bgr_rs);
			}
			$is_favorite = $this->tv->is_favorite_channel_id($channel_id, $plugin_cookies);
			if ($is_favorite)
            {
            $del_favorite_action =
                UserInputHandlerRegistry::create_action(
                    $this, 'del_favorite');
            $caption = 'Удалить из избранного';
            }
			else
			{
            $add_favorite_action =
                UserInputHandlerRegistry::create_action(
                    $this, 'add_favorite');
            $caption = 'Добавить в избранное';
			}
			#########hide#############
			$hide_channel_action =
                UserInputHandlerRegistry::create_action(
                    $this, 'hide_channel');
            $hide_channel_caption = 'Скрыть канал [CLEAR]';
			
			$restore_channel_action =
                UserInputHandlerRegistry::create_action(
                    $this, 'restore_channels_dialog');
            $restore_channel_caption = 'Восстановить скрытые каналы';
			if($hided_channels == 'no')
			{
			$view_hide_channel_action =
                UserInputHandlerRegistry::create_action(
                    $this, 'view_hide_channel_action_dialog');
            $view_hide_channel_caption = 'Показать скрытые каналы';
			}
			elseif($hided_channels == 'yes')
			{
			$view_hide_channel_action =
                UserInputHandlerRegistry::create_action(
                    $this, 'hide_hide_channel_action_dialog');
            $view_hide_channel_caption = 'Скрыть (не восстанавливать) скрытые каналы';
			}
			###########
			/* $one_rec_action =
                UserInputHandlerRegistry::create_action(
                    $this, 'one_rec');
            $one_rec_caption = 'Расписание записи каналов';
			$new_rec_action =
                UserInputHandlerRegistry::create_action(
                    $this, 'new_rec');
            $new_rec_caption = 'Запись канала по таймеру';
			$background_rec_action =
                UserInputHandlerRegistry::create_action(
                    $this, 'background_rec');
            $background_rec_caption = 'Фоновая запись канала';
			$background_stoprec_action =
                UserInputHandlerRegistry::create_action(
                    $this, 'background_stoprec');
            $background_stoprec_caption = 'Остановить запись'; */
			
			if ($is_favorite)
            {
            $menu_items[] = array(
                GuiMenuItemDef::caption => $caption,
                GuiMenuItemDef::action => $del_favorite_action,
				GuiMenuItemDef::icon_url => 'plugin_file://icons/small/fav_del.aai');
            }
			else
			{
            $menu_items[] = array(
                GuiMenuItemDef::caption => $caption,
                GuiMenuItemDef::action => $add_favorite_action,
				GuiMenuItemDef::icon_url => 'plugin_file://icons/small/fav.aai');
			}
			#########hide##############
			$menu_items[] = array(
                GuiMenuItemDef::caption => $hide_channel_caption,
                GuiMenuItemDef::action => $hide_channel_action,
				GuiMenuItemDef::icon_url => 'plugin_file://icons/small/hide_channel.aai');
			if($hide_items <> '')
			{
			$menu_items[] = array(
                GuiMenuItemDef::caption => $restore_channel_caption,
                GuiMenuItemDef::action => $restore_channel_action,
				GuiMenuItemDef::icon_url => 'plugin_file://icons/small/restore_all.aai');
			}
			##########
			/* $menu_items [] =  array( 
				GuiMenuItemDef::is_separator => true,);	
			$menu_items[] = array(
                GuiMenuItemDef::caption => $background_rec_caption,
                GuiMenuItemDef::action => $background_rec_action,
				GuiMenuItemDef::icon_url => 'plugin_file://icons/small/rec.aai');
			if (file_exists($bgr_rs)) {
			$menu_items[] = array(
                GuiMenuItemDef::caption => $background_stoprec_caption,
                GuiMenuItemDef::action => $background_stoprec_action,
				GuiMenuItemDef::icon_url => 'plugin_file://icons/small/stop_rec.aai');}
			$menu_items[] = array(
                GuiMenuItemDef::caption => $new_rec_caption,
                GuiMenuItemDef::action => $new_rec_action,
				GuiMenuItemDef::icon_url => 'plugin_file://icons/small/timer.aai');
			$menu_items[] = array(
                GuiMenuItemDef::caption => $one_rec_caption,
                GuiMenuItemDef::action => $one_rec_action,
				GuiMenuItemDef::icon_url => 'plugin_file://icons/small/shedule.aai');
			$menu_items [] =  array( 
				GuiMenuItemDef::is_separator => true,);	 */

			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)
            {
                return ActionFactory::show_title_dialog(
                    'Канал уже находится в избранном',
                    $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 ActionFactory::show_title_dialog(
                    'Канал добавлен в Избранное',
                    $this->get_sel_item_update_action(
                        $user_input, $plugin_cookies));
            }
        }
		else if ($user_input->control_id == 'del_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;

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

			return ActionFactory::show_title_dialog(
                    'Канал удален из избранного',
                    $this->get_sel_item_update_action(
                        $user_input, $plugin_cookies));
            #return $this->get_update_action(0, $user_input, $plugin_cookies);
        }
		#########hide###########
		else if ($user_input->control_id == 'hide_channel')
			{
				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);
			$title = $c->get_title();
			#hd_print("title--->$title");
			#hd_print("channel_id--->$channel_id");
			$defs = $this->make_hide_channels_defs($channel_id, $title, &$plugin_cookies);
					return  ActionFactory::show_dialog
					("Внимание!!!",
					$defs,
					true);
			
			}
		else if ($user_input->control_id == 'restore_channels_dialog')
			{
			$defs = $this->restore_hide_channels_defs($plugin_cookies);
					return  ActionFactory::show_dialog
					("Внимание!!!",
					$defs,
					true);
			}
		else if ($user_input->control_id == 'view_hide_channel_action_dialog')
			{
			$defs = $this->view_hide_channels_defs();
					return  ActionFactory::show_dialog
					("Внимание!!!",
					$defs,
					true);
			}
		else if ($user_input->control_id == 'hide_hide_channel_action_dialog')
			{
			$defs = $this->hide_hide_channels_defs();
					return  ActionFactory::show_dialog
					("Внимание!!!",
					$defs,
					true);
			}
		else if ($user_input->control_id == 'view_hide_channel_action')
			{
			$plugin_cookies->hided_channels = '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_channel_action')
			{
			$plugin_cookies->hided_channels = '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_channels')
			{
			$plugin_cookies->hide_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_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');
				#break;
			}
		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');
				#break;
			}
		#########
        else if ($user_input->control_id == 'reset_channels')
        {
		$this->session->set_channels_order(-1,'reset');
	        $this->tv->unload_channels();
	        $this->tv->newload($plugin_cookies);
	    	$media_url_ = MediaURL::decode($user_input->parent_media_url);
	    	$range = HD::create_regular_folder_range($this->get_all_folder_items($media_url_, &$plugin_cookies));
	    	return ActionFactory::update_regular_folder($range, false);		

		}
        
        return null;
    }

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

    private function get_regular_folder_item($group, $c, &$plugin_cookies)
    {
        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
            (
                ViewItemParams::icon_path => $c->get_icon_url(),
                ViewItemParams::item_detailed_icon_path => $c->get_icon_url(),
            ),
            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);
        $group = $this->tv->get_group($media_url->group_id);

        $items = array();
        foreach ($group->get_channels($plugin_cookies) as $c)
        {
            $items[] = $this->get_regular_folder_item($group, $c, $plugin_cookies);
        }
        return $items;
    }

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

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