<?php

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

class I24hM3uTv extends AbstractTv
{
    public function __construct()
    {
        parent::__construct(
            AbstractTv::MODE_CHANNELS_N_TO_M,
            I24hConfig::TV_FAVORITES_SUPPORTED,
            true);
    }

    public function get_fav_icon_url()
    {
        return I24hConfig::FAV_CHANNEL_GROUP_ICON_PATH;
    }

    private static function make_channel_id($media_url)
    {
        $id = preg_replace('/udp:\/\/@/', '', $media_url);
        $id = preg_replace('/:/', '_', $id);
        return $id;
    }

    private static function get_icon_path($channel_id)
    { return sprintf(I24hConfig::M3U_ICON_FILE_URL_FORMAT, $channel_id); }

    protected function load_channels(&$plugin_cookies)
    {
        $this->channels = new HashedArray();
        $this->groups = new HashedArray();

        if ($this->is_favorites_supported())
        {
            $this->groups->put(
                new FavoritesGroup(
                    $this,
                    '__favorites',
                    I24hConfig::FAV_CHANNEL_GROUP_CAPTION,
                    I24hConfig::FAV_CHANNEL_GROUP_ICON_PATH));
        }

        $all_channels_group = 
            new AllChannelsGroup(
                $this,
                I24hConfig::ALL_CHANNEL_GROUP_CAPTION,
                I24hConfig::ALL_CHANNEL_GROUP_ICON_PATH);

        $this->groups->put($all_channels_group);

        $m3u_lines =
            file(
                I24hConfig::M3U_FILE_URL,
                FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

        for ($i = 0; $i < count($m3u_lines); ++$i)
        {
            if (preg_match('/^#EXTINF:\d+,(.+)$/', $m3u_lines[$i], $matches) != 1)
                continue;

            $caption = $matches[1];

            if ($i + 1 >= count($m3u_lines))
                break;

            $media_url = null;

            for (++$i; $i < count($m3u_lines); ++$i)
            {
                if (preg_match('/^udp:\/\//', $m3u_lines[$i]) == 1)
                {
                    $media_url = $m3u_lines[$i];
                    break;
                }
            }

            if (is_null($media_url))
                break;

            $id = self::make_channel_id($media_url);

            $channel =
                new I24hChannel(
                    $id,
                    $caption,
                    self::get_icon_path($id),
                    $media_url,
                    -1,
                    0,
                    0);

            $this->channels->put($channel);
        }
    }

    public function get_day_epg_iterator($channel_id, $day_start_ts, &$plugin_cookies)
    { return array(); }
}

?>
