<?php

namespace Live\Src;

use Dever;
use Live\Lib\Handle;
class Api
{
	private $key = 'signature_dever_2018_jm';

	private function check()
	{
		$signature = Dever::input('signature');
        if ($signature != md5($this->key)) {
            Dever::alert('signature error');
        }
	}

    # 获取直播地址
    public function get()
    {
        $this->check();

        $data = Dever::db('live/active')->getAll(array('status' => 2));

        if ($data) {
            foreach ($data as $k => $v) {
                $data[$k]['stream'] = Dever::db('live/stream')->getAll(array('active_id' => $v['id']));
                if ($data[$k]['stream']) {
                	foreach ($data[$k]['stream'] as $k1 => $v1) {
                		if (!$v1['url_rtmp']) {
                			unset($data[$k]['stream'][$k1]);
                		}
                	}
                }
            }
            return array('active' => $data);
        } else {
            return array('active' => (object) array());
        }
    }

    # 开始推流
    public function start()
    {
        $this->check();
        $id = Dever::input('id');
        if (!$id) {
        	Dever::alert('错误的id');
        }
        $handle = new Handle();
        $handle->startLive($id);

        # 建立一个推流日志
        $log_id = $handle->saveIosLog($id);

        return array('id' => $id, 'log_id' => $log_id);
    }

    # 结束推流
    public function stop()
    {
        $this->check();
        $id = Dever::input('id');
        $log_id = Dever::input('log_id');
        if (!$id) {
        	Dever::alert('错误的id');
        }
        if (!$log_id) {
        	Dever::alert('错误的id');
        }
        $handle = new Handle();
        $handle->save($id, $log_id);

        Dever::daemon('api.save?id=' . $id . '&log_id=' . $log_id, 'live');

        //Dever::load('live/api.save?id=' . $id . '&log_id=' . $log_id);
        return array('id' => $id, 'log_id' => $log_id);
    }

    # 获取回放地址
    public function save()
    {
        $id = Dever::input('id');
        $log_id = Dever::input('log_id');
        if (!$id) {
        	Dever::alert('错误的id');
        }
        if (!$log_id) {
        	Dever::alert('错误的id');
        }
        $handle = new Handle();
        $video = Dever::config('base', 'live')->video;
        $handle->saveIosLog($id, $log_id, $video);

        # 获取这个流对应的直播信息
        

        return 'ok';
    }

    # 查看直播状态
    public function status($id)
    {
        $handle = new Handle();
        $status = $handle->getStatus($id);

        if ($status && isset($status['bps']) && $status['bps']) {
            return 1;
        } else {
            return 2;
        }
    }
}