<?php
namespace App\Http\Controllers;

use App\Path;
use App\Car;
use Illuminate\Http\Request;//這行很重要，因為它會載入request類別
use Illuminate\Http\Response;
use GuzzleHttp\Client;
use Illuminate\Support\Arr;
use Session;
use App\Http\Controllers\Controller;
use App\Camip;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;

class CanvasController extends Controller
{   
    
    // /**
    //  * 顯示應用程式中所有使用者的列表。
    //  *
    //  * @return Response
    //  */
    private $docker_ip="http://192.168.5.222:2375";

    public function index(Request $request) 
    {   
        
        
    }

    public function canvas_set(Request $request) //剛載入網頁
    {   
        $query = Path::all();
        $main=Car::all();

        $camip = camip::where('id', $request->input("canvas_id"))->first();
        if($request->input("start_x")<0){
            $camip->start_x = 0;
        }else{
            $camip->start_x = $request->input("start_x");
        }
        if($request->input("start_y")<0){
            $camip->start_y = 0;
        }else{
            $camip->start_y = $request->input("start_y");
        }        
        $camip->end_x = $request->input("end_x");
        $camip->end_y = $request->input("end_y");

        $camip->save();    
 
        return redirect('cam');
    }

    public function loadcam(Request $request) //剛載入網頁
    {   
        $query = Path::all();
        $main=Car::all();

        //目前是哪個警示條
        $alert="";
        $alert = Session::get('alert', "");
        //被選的攝影機編號
        $selectid=0;
        $selectid = Session::get('selectid', 0);
        //數資料表還有多少筆資料
        $countid=0;
        $countid = camip::SELECT('id')->count();
        //把資料表內的資料抓出來
        $camall=array();
        $camall = camip::all();
        //把最後一筆資料的id抓出來
        $lastcamid=0;
        $lastcam = camip::SELECT('id')->orderBy('id', 'desc')->first();
        if($lastcam==""){
            $lastcamid=0;
        }else{
            $lastcamid=$lastcam->id;
        }

        
        // 'selectid'=>$selectid
        ///test///
        

        //////////
 
        return View('campage',['result'=>$query,'iresult'=>$main,'countid' => $countid,'camall' => $camall,'lastcamid' => $lastcamid,'alert'=>$alert,'selectid'=>$selectid]);
    }

    public function caminsert(Request $request)//按下新增攝影機時執行
    {   
        $query = Path::all();
        $main=Car::all();

        //判斷alert要顯示什麼
        $alert="";
        //取得路徑        
        $path_id=$request->input("inputcamid");
        $path_public = public_path('campic\\'.$path_id);
        //檢查是否能連接串流，如果可，則回傳'suc'

        $process = new Process('ffmpeg.exe -rtsp_transport tcp -i '.$request->input("inputcamip").' -r 1 -ss 00:00:00 -vframes 1 -f image2 -an -y '.$path_public.'.jpg');
        $process->run();

        // executes after the command finishes
        if (!$process->isSuccessful()) {
            throw new ProcessFailedException($process);
        }

        dd ($process->getOutput());

        $out = shell_exec('ffmpeg.exe -rtsp_transport tcp -i '.$request->input("inputcamip").' -r 1 -ss 00:00:00 -vframes 1 -f image2 -an -y '.$path_public.'.jpg && echo suc');
        //檢查判斷使用者的desip有沒有多餘的符號'/'
        $destination_ip="";
        $user_inputdesip="";
        if(substr(trim($request->input("inputdesip")),0,1)=="/"){
            $destination_ip="rtmp://192.168.5.17:1935".trim($request->input("inputdesip"));
            $user_inputdesip=substr(trim($request->input("inputdesip")),1,mb_strlen(trim($request->input("inputdesip")))-1);
        }else{
            $destination_ip="rtmp://192.168.5.17:1935/".trim($request->input("inputdesip"));
            $user_inputdesip=trim($request->input("inputdesip"));
        }
        //var_dump($out);
        //如果串流抓到，則新增資料進資料庫
        if(strpos($out,'suc') !== false){
            $camip = new camip;

            $camip->id = $request->input("inputcamid");
            $camip->name = $request->input("inputcamname");
            $camip->ip = trim($request->input("inputcamip"));
            if($user_inputdesip==""){
                $camip->desip = "";
            }else{
                $camip->desip =$destination_ip;
            }
            $camip->picsite = 'campic/'.$request->input("inputcamid").'.jpg';
            $camip->status = '已儲存';

            $camip->save();
            $alert= "insertsuc";

            $container_name="";
            //判斷如果有目的串流就拋轉
            if($user_inputdesip!=""){
                ///////////////////////////////////////////////寫創建container的程式
                $container_name="Yucamtest".$request->input("inputcamid");
                //建立客戶端連線
                $client = new \GuzzleHttp\Client();
                //送出請求
                $res = $client->POST($this->docker_ip."/containers/create?name=$container_name",[
                    "headers" => ["Content-Type" => "application/json"],
                    "json" => [
                        //Image如果改名這裡要修改
                        "Image" => "ffmpeg-rtmp:latest",
                        "Env"   =>  array(
                            'SOURCE='.trim($request->input("inputcamip")),
                            'DESTINATION='.$destination_ip                   
                        ),
                        'Labels'=>array(
                            'level'=>'admin'
                        )                                        
                    ]
                ]);
                ///////////////////////////////////////////////////////寫讀取剛創的container_id程式
                //客戶端想取得這個網址的資料
                $res = $client->get($this->docker_ip."/containers/json?all=1");
                //用json解碼  陣列型態?(2維) array[1] array[2]....
                $response = json_decode($res->getBody()->__toString(), true);
                //數array
                $container_count=count($response);
                //宣告陣列
                $find_id_arr=array();
                //把要的資料抓出來(2維 )
                for($i=0;$i<$container_count;$i++){
                    array_push($find_id_arr,['Names'=>$response[$i]['Names'],'Id'=>substr($response[$i]['Id'],0,12)
                    ]);
                }
                //將多維陣列變成一維陣列
                $flatten_res = array_flatten($find_id_arr);
                //計算名子+數字陣列的個數
                $find_id_count=count($flatten_res);
                //找出名子對應的ID                
                $find_id="";
                for($i=0;$i<$find_id_count;$i++){
                    if($flatten_res[$i]=="/".$container_name){
                        $find_id=$flatten_res[$i+1];
                        break;
                    }
                }
                ///////////////////////////////////////////////////////儲存container_ID到資料庫
                Camip::where('id', $request->input("inputcamid"))                            
                        ->update(['contain_id' => $find_id]);
                ///////////////////////////////////////////////////////寫讓container執行的程式
                $res = $client->POST($this->docker_ip."/containers/".$find_id."/start");


            }
            else{
                $alert= "streamfail";
            }
        }
        else{
            $alert="insertfail";
        }

       
        return redirect('cam')->with('alert',$alert);
    }

    public function camdelete(Request $request) //刪除攝影機
    {   
        $query = Path::all();
        $main=Car::all();
        
        $camdb=Camip::where('id', $request->input("camid"))->select('desip')->get();
        $camdb_desip=$camdb[0]->desip;
        if($camdb_desip!=""){

            //////////////////////////////////////////////////先刪除contain
            //從資料表裡抓contain_id的值
            $camdb=Camip::where('id', $request->input("camid"))->select('contain_id')->get();
            $contain_id=$camdb[0]->contain_id;
            //建立客戶端連線
            $client = new \GuzzleHttp\Client();
            //暫停container
            $res = $client->POST($this->docker_ip."/containers/".$contain_id."/stop");
            //刪除container
            $res = $client->DELETE($this->docker_ip."/containers/".$contain_id);
        }

        //////////////////////////////////////////////////刪除資料庫資料的程式
        $deleteRow = camip::where('id', $request->input("camid"))->delete();

        $alert='delete';
        $selectid=$request->input("camid");

        
        return redirect('cam')->with('alert',$alert)->with('selectid',$selectid);
        
    }

    public function camupdate(Request $request) //修改攝影機
    {   
        $query = Path::all();
        $main=Car::all();

        //判斷alert要顯示什麼
        $alert="";
        $selectid=0;
        //取得路徑        
        $path_id=$request->input("updatecamid");
        $path_public = public_path('campic\\'.$path_id);
        //檢查是否能連接串流，如果可，則回傳'suc'
        $out = shell_exec('ffmpeg.exe -rtsp_transport tcp -i '.$request->input("updatecamip").' -r 1 -ss 00:00:00 -vframes 1 -f image2 -an -y '.$path_public.'.jpg && echo suc');
        //檢查判斷使用者的desip有沒有多餘的符號'/'
        $destination_ip="";
        $user_inputdesip="";
        if(substr(trim($request->input("updatecamdesip")),0,1)=="/"){
            $destination_ip="rtmp://192.168.5.17:1935".trim($request->input("updatecamdesip"));
            $user_inputdesip=substr(trim($request->input("updatecamdesip")),1,mb_strlen(trim($request->input("updatecamdesip")))-1);
        }else{
            $destination_ip="rtmp://192.168.5.17:1935/".trim($request->input("updatecamdesip"));
            $user_inputdesip=trim($request->input("updatecamdesip"));
        }
        //如果串流抓到，則'修改'資料進資料庫
        if(strpos($out,'suc') !== false){
            $camip = camip::where('id', $request->input("updatecamid"))->first();

            $camip->name = $request->input("updatecamname");
            $camip->ip = $request->input("updatecamip");
            if($user_inputdesip==""){
                $camip->desip = "";
            }else{
                $camip->desip =$destination_ip;
            }
            $camip->save();

            $alert="updatesuc";
            $selectid=$request->input("updatecamid");
            $container_name="";
            //判斷如果有目的串流就拋轉
            if($user_inputdesip!=""){
                ///////////////////////////////////////////////判斷一開始是否就有container做拋轉，如果沒有則直接新增
                //從資料表裡抓contain_id的值
                $camdb=Camip::where('id', $request->input("updatecamid"))->select('contain_id')->get();
                $contain_id=$camdb[0]->contain_id;
                if($contain_id!=""){                    
                    ///////////////////////////////////////////////先刪除舊的container                    
                    //建立客戶端連線
                    $client = new \GuzzleHttp\Client();
                    //暫停container
                    $res = $client->POST($this->docker_ip."/containers/".$contain_id."/stop");
                    //刪除container
                    $res = $client->DELETE($this->docker_ip."/containers/".$contain_id);
                }
                ///////////////////////////////////////////////寫創建container的程式
                $container_name="Yucamtest".$request->input("updatecamid");
                //建立客戶端連線
                $client = new \GuzzleHttp\Client();
                //送出請求
                $res = $client->POST($this->docker_ip."/containers/create?name=$container_name",[
                    "headers" => ["Content-Type" => "application/json"],
                    "json" => [
                        //Image如果改名這裡要修改
                        "Image" => "ffmpeg-rtmp:latest",
                        "Env"   =>  array(
                            'SOURCE='.$request->input("updatecamip"),
                            'DESTINATION='.$destination_ip                   
                        ),
                        'Labels'=>array(
                            'level'=>'admin'
                        )                                        
                    ]
                ]);
                ///////////////////////////////////////////////////////寫讀取剛創的container_id程式
                //客戶端想取得這個網址的資料
                $res = $client->get($this->docker_ip."/containers/json?all=1");
                //用json解碼  陣列型態?(2維) array[1] array[2]....
                $response = json_decode($res->getBody()->__toString(), true);
                //數array
                $container_count=count($response);
                //宣告陣列
                $find_id_arr=array();
                //把要的資料抓出來(2維 )
                for($i=0;$i<$container_count;$i++){
                    array_push($find_id_arr,['Names'=>$response[$i]['Names'],'Id'=>substr($response[$i]['Id'],0,12)
                    ]);
                }
                //將多維陣列變成一維陣列
                $flatten_res = array_flatten($find_id_arr);
                //計算名子+數字陣列的個數
                $find_id_count=count($flatten_res);
                //找出名子對應的ID                
                $find_id="";
                for($i=0;$i<$find_id_count;$i++){
                    if($flatten_res[$i]=="/".$container_name){
                        $find_id=$flatten_res[$i+1];
                        break;
                    }
                }
                ///////////////////////////////////////////////////////儲存container_ID到資料庫
                Camip::where('id', $request->input("updatecamid"))                            
                        ->update(['contain_id' => $find_id]);
                ///////////////////////////////////////////////////////寫讓container執行的程式
                $res = $client->POST($this->docker_ip."/containers/".$find_id."/start");


            }
            else{
                ///////////////////////////////////////////////////////抓BD的contain_id，如果有資料則刪除container
                //從資料表裡抓contain_id的值
                $camdb=Camip::where('id', $request->input("updatecamid"))->select('contain_id')->get();
                $contain_id=$camdb[0]->contain_id;
                if($contain_id!=""){
                    ///////////////////////////////////////////////先刪除舊的container                    
                    //建立客戶端連線
                    $client = new \GuzzleHttp\Client();
                    //暫停container
                    $res = $client->POST($this->docker_ip."/containers/".$contain_id."/stop");
                    //刪除container
                    $res = $client->DELETE($this->docker_ip."/containers/".$contain_id);

                    //設定資料表的contain_id為空值
                    $camip = camip::where('id', $request->input("updatecamid"))->first();
                    $camip->contain_id = "";
                    $camip->save();
                }             

                $alert= "streamfail";
            }


        }
        else{
            $alert="updatefail";
        }

        
        return redirect('cam')->with('alert',$alert)->with('selectid',$selectid);
    }



}