<?php

namespace App\Http\Controllers;

use App\E3SCamera;
use GuzzleHttp\Client;
use Illuminate\Http\Request;

class CameraController extends Controller
{
    //
    // 定義圖片伺服器
    public $imgserver="http://192.168.5.222:8000";

    // 定義docker server
    public $dockerserver="http://192.168.5.17:2375";

    // 定義SRS伺服器
    public $srs_host="192.168.5.17";
    public $srs_port="1935";

    //  路由方法
    //  設備管理主目錄
    public function index()
    {
        // 取得所有設備資訊
        $devices_info=$this->get_all_device();
        // 取得攝影機群組與清單
        $groups=$devices_info[0];
        $camera_list=$devices_info[1];

        //        return $camera_list["RD"];
        return view("Camera",["title"=>"攝影機管理","groups"=>$groups,"camera_list"=>$camera_list]);
    }

    public function index_show($id)
    {
        // 取得所有設備資訊
        $devices_info = $this->get_all_device();
        // 取得攝影機群組與清單
        $groups = $devices_info[0];
        $camera_list = $devices_info[1];

        // 驗證並取得單一攝影機資訊
        $camera_info = $this->get_camera_info($id);

        if ($camera_info == "查無此設備或無此權限") {
            // 無此權限或無此設備回傳 404頁面
            return abort(404);
//            return "something error";
        } else {
            return view("Camera", ["title" => "攝影機管理", "groups" => $groups, "camera_list" => $camera_list,"camera_info"=>$camera_info]);
        }
    }

    // 新增頁面
    public function insert_index()
    {
        // 取得所有攝影機資訊
        $all_devices=$this->get_all_device();
        // 取得攝影機群組與清單
        $groups=$all_devices[0];
        $camera_list=$all_devices[1];

//        return $camera_list["RD"];
        return view("Camera_Insert",["title"=>"新增攝影機","groups"=>$groups,"camera_list"=>$camera_list]);
    }

    // 設備新增處理
    public function insert(Request $request)
    {
        //  測試是否有此攝影機
        $client=new Client();
        $response=$client->request('post','http://'.$request->ip.'/device/info/mac');

        if($response->getStatusCode()==200){

            // 建立e3scamera物件
            $e3scamera=new E3SCamera;

            // 檢查是否ip重複
            if($e3scamera->where("ip",'=',$request->ip)->count()==0){
                // 檢查是否群組內名稱重複
                if($e3scamera->where("group",'=',$request->group)
                        ->where("name","=",$request->name)
                        ->count()==0){
                    // roi data to json
                    $roi=json_decode($request->roi);
                    // save to db
                    $e3scamera->ip=$request->ip;
                    $e3scamera->group=$request->group;
                    $e3scamera->name=$request->name;
                    $e3scamera->threshold=$request->threshold;
                    $e3scamera->mac=json_decode($response->getBody())->mac;
                    $e3scamera->imgserver=$this->imgserver;
                    $e3scamera->rtmp_stream=sprintf('http://%s/%s/%s.flv',$this->srs_host,$request->group,$request->name);
                    $e3scamera->roi_top=$roi->top;
                    $e3scamera->roi_bottom=$roi->bottom;
                    $e3scamera->roi_left=$roi->left;
                    $e3scamera->roi_right=$roi->right;
                    $e3scamera->save();

                    // 啟動container拋轉串流至SRS伺服器
                    $res = $client->POST($this->dockerserver."/containers/create?name=".$request->group.$request->name."_rtmp",[
                        "headers" => ["Content-Type" => "application/json"],
                        "json" => [
                            "Image" => "rtsp2rtmp",
                            "Env"   =>  array(
                                'RTSP_HOST='.$request->ip,
                                'RTSP_PORT=8554',
                                'RTSP_KEY=stream0',
                                'EADA_HOST='.$this->srs_host,
                                'EADA_PORT='.$this->srs_port,
                                'MQTT_TOPIC='.$request->group.'/'.$request->name
                            ),
                            'Labels'=>array(
                                'level'=>'admin',
                                'des_stream'=>$request->group.$request->name."_rtmp"
                            ),
                            'RestartPolicy'=>array(
                                'name'=>'always',
                                'MaximumRetryCount'=>0
                            )
                        ]
                    ]);

                    // 啟動此container
                    $response = json_decode($res->getBody()->__toString(), true);
                    $container_id=$response["Id"];
                    $res = $client->POST($this->dockerserver."/containers/".$container_id."/start");


                    // 新增成功
                    $msg="新增成功";
                }else{
                    // 資料庫內已有相同名稱之設備
                    $msg="已有相同名稱之設備";
                }
            }else{
                // 設備ip重複 or 已有此設備
                $msg="設備ip重複或已有此設備";
            }
        }else{
            // ip錯誤查無此設備
            $msg='ip錯誤或無此設備';
        }

        // 顯示結果至Insert主頁
        $all_devices=$this->get_all_device();
        // 取得攝影機群組與清單
        $groups=$all_devices[0];
        $camera_list=$all_devices[1];

        if(isset($msg)){
            return view("Camera_Insert",["title"=>"新增攝影機","groups"=>$groups,"camera_list"=>$camera_list,"error_msg"=>$msg]);
        }else{
            return view("Camera_Insert",["title"=>"新增攝影機","groups"=>$groups,"camera_list"=>$camera_list]);
        }
    }

    // 修改頁面
    public function modify_index($id)
    {
        // 顯示設備清單
        $devices_info=$this->get_all_device();
        $groups=$devices_info[0];
        $camera_list=$devices_info[1];

        // 驗證並取得單一攝影機資訊
        $camera_info=$this->get_camera_info($id);

        if($camera_info=="查無此設備或無此權限"){
            // 無此權限或無此設備回傳 404頁面
            return abort(404);
        }else{
            return view('Camera_Modify',["title"=>"修改攝影機","groups"=>$groups,"camera_list"=>$camera_list,"camera_info"=>$camera_info]);

        }

    }

    public function modify(Request $request)
    {
        // 帳戶權限驗證

        //  測試是否有此攝影機
        $client=new Client();
        $response=$client->request('post','http://'.$request->ip.'/device/info/mac');

        if($response->getStatusCode()==200){

            // 建立e3scamera物件
            $e3scamera=new E3SCamera;

            // 檢查是否ip重複
            if($e3scamera->where("id","!=",$request->id)->where("ip",'=',$request->ip)->count()==0){
                // 檢查是否群組內名稱重複 排除id 等於欲修改之 id
                if($e3scamera->where("id","!=",$request->id)
                        ->where("group",'=',$request->group)
                        ->where("name","=",$request->name)
                        ->count()==0){
                    // roi data to json
                    $roi=json_decode($request->roi);
                    // update to db
                    $e3scamera->where("id","=",$request->id)
                        ->update(["ip"=>$request->ip,"group"=>$request->group,"name"=>$request->name,
                            "threshold"=>$request->threshold,"mac"=>json_decode($response->getBody())->mac,
                            "imgserver"=>$this->imgserver,"roi_top"=>$roi->top,"roi_bottom"=>$roi->bottom,
                            "roi_left"=>$roi->left,"roi_right"=>$roi->right]);

                    // 更新成功
                    $msg="更新成功";
                }else{
                    // 資料庫內已有相同名稱之設備
                    $msg="已有相同名稱之設備";
                }
            }else{
                // 設備ip重複 or 已有此設備
                $msg="設備ip重複或已有此設備";
            }
        }else{
            // ip錯誤查無此設備
            $msg='ip錯誤或無此設備';
        }

        // 顯示結果至Insert主頁
        $all_devices=$this->get_all_device();
        // 取得攝影機群組與清單
        $groups=$all_devices[0];
        $camera_list=$all_devices[1];

        // 回傳原先修改中設備資訊
        // 驗證並取得單一攝影機資訊
        $camera_info=$this->get_camera_info($request->id);

        if($camera_info=="查無此設備或無此權限"){
            // 無此權限或無此設備回傳 404頁面
            return abort(404);
        }

        if(isset($msg)){
            return view("Camera_modify",["title"=>"修改攝影機","groups"=>$groups,"camera_list"=>$camera_list,"camera_info"=>$camera_info,"error_msg"=>$msg]);
        }else{
            return view("Camera_modify",["title"=>"修改攝影機","groups"=>$groups,"camera_info"=>$camera_info,"camera_list"=>$camera_list]);
        }
    }

    //刪除攝影機
    public function drop(Request $request){
        // 驗證使用者權限
        $e3scamera=new E3SCamera;
        $cam=$e3scamera->where('id','=',$request->id)->delete();

        // 顯示結果至Insert主頁
        $all_devices=$this->get_all_device();
        // 取得攝影機群組與清單
        $groups=$all_devices[0];
        $camera_list=$all_devices[1];

        return view("Camera", ["title" => "攝影機管理", "groups" => $groups, "camera_list" => $camera_list,"error_msg"=>"刪除編號".$request->id."成功"]);
    }

    // 公用方法
    // 取得所有設備清單 回傳 群組 設備名稱與id
    public function get_all_device(){
        $e3scamera=new E3SCamera;
        $groups=$e3scamera->distinct('group')->get('group');
        $rowdata=$e3scamera->select("id","group","name")->get();

        // 建立攝影機清單
        $camera_list=array();
        foreach ($rowdata as $data){
            if(array_key_exists($data->group,$camera_list)){
                array_push($camera_list[$data->group],array("name"=>$data->name,"id"=>$data->id));
            }else{
                $camera_list[$data->group]=array(array("name"=>$data->name,"id"=>$data->id));
            }
        }

        return [$groups,$camera_list];
    }

    // 驗證使用者 並取得單一設備訊息
    public function get_camera_info($id)
    {
        // 帳戶權限驗證
        $e3scamera=E3SCamera::where('id','=',$id)->get();

        if($e3scamera->count()==0){
            return "查無此設備或無此權限";
        }else{
            // 設備資訊
            $camera_info=array(
                "id"=>$e3scamera[0]->id,
                "ip"=>$e3scamera[0]->ip,
                "group"=>$e3scamera[0]->group,
                "name"=>$e3scamera[0]->name,
                "threshold"=>$e3scamera[0]->threshold,
                "roi"=>array(
                    "left"=>$e3scamera[0]->roi_left,
                    "top"=>$e3scamera[0]->roi_top,
                    "right"=>$e3scamera[0]->roi_right,
                    "bottom"=>$e3scamera[0]->roi_bottom,
                )
            );
            return $camera_info;
        }
    }
}
