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

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

class Flussonic_MainScreen extends TvGroupListScreen implements UserInputHandler
{
    const ID = 'main_screen';

    const Version = '2.0.7';
    ///////////////////////////////////////////////////////////////////////

    protected $tv;

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

    public function __construct($tv, $folder_views)
    {
        parent::__construct($tv, $folder_views);

        $this->tv = $tv;

        UserInputHandlerRegistry::get_instance()->register_handler($this);
    }

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

    public function get_action_map(MediaURL $media_url, &$plugin_cookies)
    {
        $setup_view = ActionFactory::open_folder(FlussonicSetupScreen::get_media_url_str(), '%tr%t5'); //Настройки
        $setup_view['caption'] = '%tr%t5'; //Настройки

        if(isset($plugin_cookies->isTokenValid)){
            hd_print("Skip token validation");
            $isTokenValid = $plugin_cookies->isTokenValid;
        }
        else if(!isset($plugin_cookies->token)){
            $isTokenValid = '0';
        } else {
            $source = HD::check_token(trim(FlussonicConfig::CHANNEL_LIST_HOST."/ott/m3u8-dune/".$plugin_cookies->token."/playlist.m3u8"));
            //$source = HD::check_token(trim(FlussonicConfig::CHANNEL_LIST_HOST2."/pl/m3u8-dune/".$plugin_cookies->token."/pl.m3u8"));

            if ($source === "nottoken" || $source == "Token not found"){
				$source = HD::check_token(trim(FlussonicConfig::CHANNEL_LIST_HOST2."/pl/m3u8-dune/".$plugin_cookies->token."/pl.m3u8")); //если первый не идёт, скачать этот
			}

            if ($source === "nottoken"|| $source == ""){
                $plugin_cookies->isTokenValid = '0';
            } else {
                $plugin_cookies->isTokenValid = '1';
            }
        }

        if ($isTokenValid == '0') {
            return array(
                GUI_EVENT_KEY_ENTER => $setup_view,
                GUI_EVENT_KEY_PLAY => $setup_view,
                GUI_EVENT_KEY_B_GREEN => $setup_view
            );
        }
        $action             = UserInputHandlerRegistry::create_action($this, 'whats_new');
        $action['caption']  = 'Новое в версии ' . FlussonicConfig::PluginVersion;
        $balance            = UserInputHandlerRegistry::create_action($this, 'check_balance');
        $balance['caption'] = '%tr%t43';//Подписка

        return array(
            GUI_EVENT_KEY_ENTER => ActionFactory::open_folder(),
            GUI_EVENT_KEY_PLAY => ActionFactory::tv_play(),
            GUI_EVENT_KEY_B_GREEN => $setup_view,
            //GUI_EVENT_KEY_D_BLUE => $action
              GUI_EVENT_KEY_C_YELLOW => $balance
        );

    }

    private function _whats_new_dialog()
    {
        $doc = HD::http_get_document('http://zlostnyi.tech/dune/telestars/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 == FlussonicConfig::PluginVersion) {
                $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('Изменения в версии ' . FlussonicConfig::PluginVersion, $defs);
    }
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////
    private function _check_balance_dialog(&$plugin_cookies) {
        $defs = array();
        try {
		    $billing_id = isset($plugin_cookies->billing_id) ? $plugin_cookies->billing_id : 0;
		    $token = isset($plugin_cookies->token) ? $plugin_cookies->token : "0";
            $packet_info = FlussonicConfig::get_packet_info(sprintf(FlussonicConfig::USER_INFO, $plugin_cookies->token), $billing_id);
            if (count($packet_info) == 0){
                ControlFactory::add_label($defs, '%tr%t40', "%tr%t50"); // Пакет , "Не веден ключ"
                ControlFactory::dd_label($defs, '%tr%t41', "-"); // Действителен до , -
            }
            else if(count($packet_info) == 1 && ($packet_info[0]['exp'] == "404" || $packet_info[0]['exp'] == "401" || $packet_info[0]['exp'] == "0")){
                ControlFactory::add_label($defs, "", $packet_info[0]['packet']);
            } else {
                foreach($packet_info as $p_info){
                    ControlFactory::add_label($defs, "%tr%t40", $p_info['packet']); //Пакет:
                    ControlFactory::add_label($defs, "%tr%t41", $p_info['exp']); //Действителен до:
                }
            }
        } catch (Exception $e) {
            hd_print("Can't fetch doc, used error text.");

            ControlFactory::add_label($defs, "%tr%t48", "%tr%t47"); //Ошибка!
            ControlFactory::add_label($defs, "%tr%t49", "%tr%t50"); //Причина:

        }

        ControlFactory::add_close_dialog_button($defs, 'OK', 150);

        return ActionFactory::show_dialog('%tr%t42', $defs); //Статус подписки
    }
    ////////////////////////////////////////////////////////////////////////////////////////////////////////
    public function handle_user_input(&$user_input, &$plugin_cookies)
    {
        hd_print('main_screen: handle_user_input:');
        foreach ($user_input as $key => $value)
            hd_print("  $key => $value");

        switch ($user_input->control_id) {
            case 'settings':
                return ActionFactory::open_folder(FlussonicSetupScreen::get_media_url_str(), "%tr%t8"); //Настройки
            case 'whats_new':
                return $this->_whats_new_dialog();
            case 'check_balance':
                return $this->_check_balance_dialog(&$plugin_cookies);
        }

        return null;
    }
}

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