<?php
namespace Live\Lib;

use Dever;

class Handle
{
    public function method($config)
    {
        if ($config['type'] == 1) {
            $method = new Qiniu($config);
        }

        return $method;
    }

    # 启动
    public function start($id)
    {
        $info = Dever::db('live/stream')->one($id);
        $config = Dever::db('live/info')->one($info['live_id']);
        $method = $this->method($config);
        $stream = $method->start($info['key']);
    }

    # 禁播
    public function stop($id)
    {
        $info = Dever::db('live/stream')->one($id);
        $config = Dever::db('live/info')->one($info['live_id']);
        $method = $this->method($config);
        $stream = $method->stop($info['key']);
    }

    # 保存
    public function save($id, $log_id)
    {
        $info = Dever::db('live/stream')->one($id);
        $config = Dever::db('live/info')->one($info['live_id']);
        $method = $this->method($config);

        $info_update['where_id'] = $info['id'];
        $info_update['status'] = 3;

        Dever::db('live/stream')->update($info_update);

        Dever::db('live/stream_ios_log')->update(array('edate' => time(), 'where_id' => $log_id));

        return true;
    }

    # 建立ios直播日志
    public function saveIosLog($id, $log_id = false, $video = false)
    {
        $info = Dever::db('live/stream')->one($id);

        if (!$log_id) {
            $time = time();
            $data['sdate'] = $time;
            $data['stream_id'] = $id;
            $data['live_id'] = $info['live_id'];
            $data['active_id'] = $info['active_id'];
            $id = Dever::db('live/stream_ios_log')->insert($data);
        } else {

            $config = Dever::db('live/info')->one($info['live_id']);
            $log = Dever::db('live/stream_ios_log')->one($log_id);
            $method = $this->method($config);
            $log['sdate'] = intval($log['sdate']);
            $log['edate'] = intval($log['edate']);

            try {
                $data['url_m3u8'] = $config['host'] . $method->save($info['key'],$log['sdate'], $log['edate']);
                //$data['url_mp4'] = $config['host'] . $method->save($info['key'], $log['sdate'], $log['edate'], 'mp4');
                $data['url_mp4'] = '';
                $data['url_mp4'] = $config['host'] . $method->save($info['key'], $log['sdate'], $log['edate'], 'mp4');
            } catch (\Exception $e) {
                $data['url_m3u8'] = $data['url_mp4'] = '';
            }

            if (!$data['url_m3u8']) {
                return;
            }
            $data['where_id'] = $log_id;
            Dever::db('live/stream_ios_log')->update($data);
            $id = $log_id;

            if ($video) {
                $this->createUrl($video, $method, $config, $info);
            }
        }
        
        return $id;
    }

    # 生成回放地址
    public function createUrl($video, $method, $config, $info)
    {
        $where[$video['stream_id']] = $info['id'];
        $data = Dever::db($video['table'])->state($where);
        if ($data) {
            foreach ($data as $k => $v) {
                $this->createUrlOne($v, $video, $method, $config, $info);
            }
        }
    }

    public function createUrlOne($data, $video, $method, $config, $info)
    {
        if ($data[$video['sdate']] > 0 && $data[$video['edate']] > 0) {

            $data[$video['sdate']] = intval($data[$video['sdate']]);
            $data[$video['edate']] = intval($data[$video['edate']]);

            try {
                $url_m3u8 = $config['host'] . $method->save($info['key'],$data[$video['sdate']], $data[$video['edate']]);
                $url_mp4 = '';
                $url_mp4 = $config['host'] . $method->save($info['key'], $data[$video['sdate']], $data[$video['edate']], 'mp4');
            } catch (\Exception $e) {
                $url_m3u8 = $url_mp4 = '';
            }

            if (!$url_m3u8) {
                return false;
            }

            Dever::db($video['table'])->update(array('where_id' => $data['id'], $video['url_m3u8'] => $url_m3u8, $video['url_mp4'] => $url_mp4));

            return array('id' => $data['id'], 'm3u8' => $url_m3u8, 'mp4' => $url_mp4);
        }

        return false;
    }

    # 开始直播
    public function startLive($id)
    {
        $info = Dever::db('live/stream')->one($id);
        $config = Dever::db('live/info')->one($info['live_id']);
        $method = $this->method($config);

        $data['where_id'] = $info['id'];
        $data['status'] = 2;

        Dever::db('live/stream')->update($data);
    }

    # 初始化流
    public function init($id, $name = '')
    {
        $info = Dever::db('live/stream')->one($id);
        if ($info['url_rtmp']) {
            return;
        }
        if ($name) {
            $info['key'] = $name;
        }

        return $this->get($info, true);
    }

    # 获取流的直播状态
    public function getStatus($info)
    {
        if (!is_array($info)) {
            $info = Dever::db('live/stream')->one($info);
        }

        $config = Dever::db('live/info')->one($info['live_id']);
        
        $method = $this->method($config);

        $status = array();

        try {
            $status = $method->getLiveStatus($info['key']);
        } catch (\Exception $e) {
            $status = array();
        }

        return $status;
    }

    # 获取流信息 定时跑
    public function get($info, $create = false)
    {
        if (!is_array($info)) {
            $info = Dever::db('live/stream')->one($info);
        }

        $config = Dever::db('live/info')->one($info['live_id']);
        
        $method = $this->method($config);

        if ($create) {
            $stream = $method->create($info['key']);
        } else {
            $stream = $method->getInfo($info['key']);
        }

        # 根据上次得到推流地址的时间计算下次应该得到的地址
        if (!$info['live_date']) {
            $info['live_date'] = 0;
        }
        $time = time();
        $num = $info['times'];
        if ($time - $info['live_date'] > $num) {
            $rtmp = $method->getRtmp($info['key'], $info['times'] * 3600);
        }

        if (!$info['url_rtmp']) {
            $url = $method->getPlay($info['key']);
        }

        $status = array();
        $history = array();

        try {
            $status = $method->getLiveStatus($info['key']);
        } catch (\Exception $e) {
            $status = array();
        }

        try {
            $history = $method->history($info['key']);
        } catch (\Exception $e) {
            $history = array();
        }

        $data['where_id'] = $info['id'];
        if (isset($rtmp) && $rtmp) {
            $data['live'] = $rtmp;
            $data['live_date'] = $time;
        }
        
        if (isset($url) && isset($url['rtmp']) && $url['rtmp']) {
            $data['url_rtmp'] = $url['rtmp'];
            $data['url_hls'] = $url['hls'];
            $data['url_hdl'] = $url['hdl'];
            $data['url_pic'] = $url['pic'];
        }

        $live = Dever::json_decode($info['info']);

        # 直播信息
        if ($stream) {
            $live['info'] = $stream;
        }
        
        # 直播状态
        if ($status) {
            $live['live'] = $status;
        }

        # 直播历史
        if ($history) {
            $live['history'] = $history;
            if (isset($history['items']) && $history['items']) {
                foreach ($history['items'] as $k => $v) {
                    $this->saveLog($info['id'], $v['start'], $v['end']);
                }
            }
        }

        if ($status) {
            $data['status'] = 2;
        } else {
            $data['status'] = 1;
        }

        $data['info'] = Dever::json_encode($live);

        Dever::db('live/stream')->update($data);

        return $data;
    }

    # 建立直播日志
    public function saveLog($id, $sdate, $edate)
    {
        $info = Dever::db('live/stream')->one($id);

        $data['sdate'] = $sdate;
        $data['edate'] = $edate;
        $data['stream_id'] = $id;
        $data['live_id'] = $info['live_id'];
        $data['active_id'] = $info['active_id'];
        $log = Dever::db('live/stream_log')->one($data);

        if (!$log) {
            $id = Dever::db('live/stream_log')->insert($data);
        }
        
        return $id;
    }
}
