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

require_once 'lib/hashed_array.php';
require_once 'lib/tv/abstract_tv.php';
require_once 'lib/tv/default_epg_item.php';
require_once 'lib/tv/epg_iterator.php';

require_once 'iptv_channel.php';
require_once 'iptv_settings.php';
///////////////////////////////////////////////////////////////////////////

class IptvTv extends AbstractTv
{
    private $session;

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

    public function __construct($session)
    {
        $this->session = $session;

        parent::__construct(
            AbstractTv::MODE_CHANNELS_1_TO_N,
            true,
            false);
    }

    public function get_fav_icon_url()
    {
        return $this->session->get_genre_icon('favorites.png');
    }

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

    protected function load_channels(&$plugin_cookies)
    {
        $this->session->check_logged_in();

        $settings = $this->session->get_settings();
        $buffering_ms = $settings->http_caching->value;
        $default_timeshift_hours = $settings->timeshift->value;
        $timeshift_hours = $default_timeshift_hours;
        $this->channels = new HashedArray();
        $this->groups = new HashedArray();

        $this->groups->put(
            new FavoritesGroup(
                $this,
                '__favorites',
                SERVICE_FAVORITES,
                $this->session->get_genre_icon('tv_favorites.png')));

        $this->groups->put(
            new AllChannelsGroup(
                $this,
                SERVICE_ALL_CHANNELS,
                $this->session->get_genre_icon('tv_all.png')));

        $num_groups = 0;
        $num_channels = 0;
        $num_protected = 0;
        $num_have_archive = 0;
        foreach ($this->session->get_channel_list()->groups as $g)
        {
            $iptv_group = new DefaultGroup(
                $g->id,
                $g->name,
                $this->session->get_group_icon($g->original_icon));
            $this->groups->put($iptv_group);
            $num_groups++;

            foreach ($g->channels as $c)
            {
                $have_archive = isset($c->have_archive) ?
                ($c->have_archive == 1) : false;
                $is_protected = isset($c->censored) ?
                ($c->censored == 1) : false;
                
                // TODO: timeshift
                

                $iptv_channel = new IptvChannel(
                    $c->id,
                    $c->name,
                    $this->session->get_channel_icon($c->icon),
                    $have_archive, $is_protected,
                    $buffering_ms, $timeshift_hours,
                    $this->session);
                $this->channels->put($iptv_channel);

                $iptv_channel->add_group($iptv_group);
                $iptv_group->add_channel($iptv_channel);

                $num_channels++;
                if ($is_protected)
                    $num_protected++;
                if ($have_archive)
                    $num_have_archive++;
            }
        }

        hd_print("iptv: $num_groups groups and ".
            "$num_channels channels ($num_have_archive have archive, ".
            "$num_protected protected)");
    }

    public function get_tv_info(MediaURL $media_url, &$plugin_cookies)
    {
        $this->session->ensure_logged_in($plugin_cookies);

        return parent::get_tv_info($media_url, $plugin_cookies);
    }

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

    public function get_tv_stream_url($playback_url, &$plugin_cookies)
    {
        return $this->session->api_get_stream_url($playback_url);
    }

    public function get_tv_playback_url($channel_id, $archive_ts, $protect_code, &$plugin_cookies)
    {
        $settings = $this->session->get_settings();
        $timeshift_hours = $settings->timeshift->value;
        
        $this->ensure_channels_loaded($plugin_cookies);

        $url = sprintf(IPTV_GET_URL_URL,
            IPTV::$SERVER,
            $this->session->get_sid_name(),
            $this->session->get_sid(),
            $channel_id);

        if (intval($archive_ts) > 0){
            $archive_ts = intval($archive_ts - ($timeshift_hours * 3600));
            $url .= "&start=$archive_ts";
        }
        if (isset($protect_code) && $protect_code !== '')
            $url .= "&protect_code=$protect_code";
        $this->session->extend_session();
        return $url;
    }

    ///////////////////////////////////////////////////////////////////////
    // API Favorites.

    public function load_api_fav_channels(&$plugin_cookies)
    {
        return $this->session->api_get_fav_channels();
    }

    public function add_api_fav_channels($channel_id)
    {
        return $this->session->api_add_fav_channels($channel_id);
    }

    public function update_api_fav_channels($channel_ids)
    {
        return $this->session->api_update_fav_channels($channel_ids);
    }
    
    ///////////////////////////////////////////////////////////////////////

    public function get_day_epg_iterator($channel_id, $day_start_ts, &$plugin_cookies)
    {
        $this->ensure_channels_loaded($plugin_cookies);
        $day_str = gmstrftime('%d%m%y', $day_start_ts);
        $url = sprintf(IPTV_EPG_URL,
            IPTV::$SERVER,
            $this->session->get_sid_name(),
            $this->session->get_sid(),
            $channel_id,
            $day_str);

        try
        {
            $iptv_epg = $this->session->api_call($url);
        }
        catch (Exception $e)
        {
            throw $this->session->dune_api_exception($e,
                'EPG request failed.',
                true);
        }

        $epg_items = array();
        $settings = $this->session->get_settings();
        $timeshift_hours = $settings->timeshift->value;
        foreach ($iptv_epg->epg as $epg)
        {
            $progname = $epg->progname;

            $arr = explode("\n", $epg->progname, 2);
            $name = count($arr) >= 1 ? trim($arr[0]) : '';
            $description = count($arr) == 2 ? $arr[1] : '';

            $start = intval($epg->ut_start + ($timeshift_hours * 3600));
            $end = -1;

            $epg_items[] = new DefaultEpgItem(
                $name, $description, $start, $end);
        }
        $day_start_ts = $day_start_ts - 86400;
        $this->session->extend_session();
        return new EpgIterator($epg_items, $day_start_ts, $day_start_ts + (3*86400));
    }

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

    public function folder_entered(MediaURL $media_url, &$plugin_cookies)
    {
        if (!isset($media_url->screen_id) ||
            $media_url->screen_id === TvGroupListScreen::ID)
        {
            $this->session->logout();
        }

        $this->session->ensure_logged_in($plugin_cookies);
    }

    // Hook for adding special group items.
    public function add_special_groups(&$items)
    {
        return array();
        array_unshift($items,
            array
            (
                PluginRegularFolderItem::media_url =>
                MediaURL::encode(
                    array
                    (
                        'screen_id' => IptvVodRootScreen::ID,
                        )),
                PluginRegularFolderItem::caption => 'Videoteka',
                PluginRegularFolderItem::view_item_params => array
                (
                    ViewItemParams::icon_path =>
                    $this->session->get_icon('mov_root.png')
                    )
                ));
    }
}

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