<?php

namespace App\Http\Controllers;

use App\E3SCamera;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Http\Request;

class AIViewController extends Controller
{
    public $imgserver="http://192.168.5.222:8000";
    public $influxdb="http://192.168.5.17:8086";

    public function index(Request $request)
    {
        date_default_timezone_set("Asia/Taipei");
//        dd(date("Y-m-d H:i:s",strtotime("2019-12-12T10:13:41Z")));
        // 圖片伺服器定義
//        $imgserver="http://192.168.5.222:8000";
        // 取得最近10筆紀錄
        $rowdata=$this->getresult(10);
//        dd($rowdata);
//        dd(array_search("time",$rowdata[0]));
        $time=array_search("time",$rowdata[0]);
        $id=array_search("id",$rowdata[0]);
        $snapshot=array_search("snapshot",$rowdata[0]);
        $score=array_search("score",$rowdata[0]);
        // 時區轉換
        for ( $i=0 ; $i<count($rowdata[1]); $i++ ) {
            $utctime=$rowdata[1][$i][$time];
            $rowdata[1][$i][$time]=date("Y-m-d H:i:s",strtotime($utctime));
        }

        // 取得所有設備及清單
        $e3scamera=new E3SCamera;
        $groups=$e3scamera->distinct('group')->get('group');
        $camdata=$e3scamera->select("id","group","name","rtmp_stream")->get();
        // 建立攝影機清單
        $camera_list=array();
        foreach ($camdata as $data){
            if(array_key_exists($data->group,$camera_list)){
                array_push($camera_list[$data->group],array("name"=>$data->name,"id"=>$data->id,"rtmp_stream"=>$data->rtmp_stream));
            }else{
                $camera_list[$data->group]=array(array("name"=>$data->name,"id"=>$data->id,"rtmp_stream"=>$data->rtmp_stream));
            }
        }
        // dd($camera_list);
        // 新增門口機設備清單
        $client=new \GuzzleHttp\Client();
        try {
            $res = $client->request('GET',sprintf("http://%s:%s",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT"))."/device/select/all");
            $status_code=$res->getStatusCode();
        }catch (RequestException $e){
            if (!$e->hasResponse()) {
                // 伺服器沒有回應
                $status_code=503;
            }
        }
        if ($status_code!=200){
            return abort("500","伺服器無法回應");
        }
        $jsondata=json_decode($res->getBody()->__toString(),true);
//        dd($jsondata);
        $srs=sprintf("http://%s:%s",env("SRS_SERVER_HOST"),env("SRS_SERVER_PORT"));
        foreach ($jsondata['Data'] as $wrist_camera){
            if($wrist_camera['Enabled']==true){
                if(array_key_exists("RD",$camera_list)){
                    array_push($camera_list[$data->group],array("name"=>$wrist_camera["Location"],"id"=>$wrist_camera["ID"],"rtmp_stream"=>sprintf("%s/%s/%s.flv",$srs,"RD",$wrist_camera["ID"])));
                }else{
                    $camera_list["RD"]=array(array("name"=>$wrist_camera["Location"],"id"=>$wrist_camera["ID"],"rtmp_stream"=>sprintf("%s/%s/%s.flv",$srs,"RD",$wrist_camera["ID"])));
                }
            }
        }
        $msg=$request->session()->get('Tusername');
        return view("FaceAI",["msg"=>$msg,"title"=>"AI人臉辨識","data"=>$rowdata[1],"time"=>$time,"id"=>$id,"snapshot"=>$snapshot,"score"=>$score,"imgserver"=>$this->imgserver,"groups" => $groups, "camera_list" => $camera_list,"newimgserver"=>sprintf("http://%s:%s",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT"))]);
    }

//    取得最近幾筆結果
    public function getresult($limlit)
    {

        $client = new \GuzzleHttp\Client();
        $res = $client->request('GET', $this->influxdb.'/query?q=select+*+from+rd01+order+by+DESC+limit+'.$limlit.'&db=FACE');
        // 將json string 轉換成 array
        $jsondata=json_decode($res->getBody()->__toString(),true);
        $measurement=$jsondata["results"][0]["series"][0]["name"];
        $columns=$jsondata["results"][0]["series"][0]["columns"];
        $values=$jsondata["results"][0]["series"][0]["values"];
        return [$columns,$values];
    }


    public function new_face_index()
    {
        return view('NewFace');
    }

    public function new_face_broadcast(Request $request)
    {
        if($request->id != null and $request->score != null and $request->snapshot != null and $request->time != null){
            $facedata=["time"=>$request->time,"id"=>$request->id,"imgserver"=>$this->imgserver,"snapshot"=>$request->snapshot,"score"=>$request->score];
            broadcast(new \App\Events\FaceEvent($facedata));
        }else{
            return "error";
        }
//        broadcast(new \App\Events\FaceEvent($request->all()));
    }
}
