<?php

namespace App\Http\Controllers;

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

class SearchController extends Controller
{
    public $imgserver="http://192.168.5.222:8000";
    public $influxdb="http://192.168.5.17:8086";
    //
    public function index()
    {
        // 取得所有設備資訊
        $devices_info=$this->get_all_device();
        // 取得攝影機群組與清單
        $groups=$devices_info[0];
        $camera_list=$devices_info[1];

        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));
        }

        return view("Search",["title"=>"人員查詢","data"=>$rowdata[1],"time"=>$time,"id"=>$id,"snapshot"=>$snapshot,"score"=>$score,"imgserver"=>$this->imgserver,"groups"=>$groups,"camera_list"=>$camera_list]);
    }

    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 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 search(Request $request){
        // 取得所有設備資訊
        $devices_info=$this->get_all_device();
        // 取得攝影機群組與清單
        $groups=$devices_info[0];
        $camera_list=$devices_info[1];

//        dd($request->input('id'),$request->input('start_time'),$request->input('end_time'))
        $stime=$this->transtime($request->input('start_time'));
        $etime=$this->transtime($request->input('end_time'));
        $find_id=$request->input('id');
//        dd($stime);
        $client = new \GuzzleHttp\Client();
        $res = $client->request('GET', $this->influxdb.'/query?q=select+*+from+rd01+where+"id"=\''.$find_id.'\'+and time+>=\''.$stime.'\'+and time<=\''.$etime.'\'+order+by+ASC+ tz(\'Asia/Taipei\') &db=FACE');
        // 將json string 轉換成 array
        $jsondata=json_decode($res->getBody()->__toString(),true);
        if(isset($jsondata["results"][0]["series"])) {
            $measurement = $jsondata["results"][0]["series"][0]["name"];
            $columns = $jsondata["results"][0]["series"][0]["columns"];
            $values = $jsondata["results"][0]["series"][0]["values"];

            $rowdata = [$columns, $values];

            $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));
            }
//            dd($rowdata);
            return view("Search",["title"=>"人員查詢","data"=>$rowdata[1],"time"=>$time,"id"=>$id,"snapshot"=>$snapshot,"score"=>$score,"imgserver"=>$this->imgserver,"groups"=>$groups,"camera_list"=>$camera_list]);
        }
        else{
            $noresult="查無資料";
            return view("Search",["title"=>"人員查詢","data"=>$noresult,"imgserver"=>$this->imgserver,"groups"=>$groups,"camera_list"=>$camera_list]);
        }
    }

    public function transtime($str){
        $day_list=[' 凌晨 ',' 凌晨 12',' 早上 ',' 上午 ',' 中午 ',' 下午 ',' 晚上 '];

        foreach ($day_list as $item) {
            if (strpos($str,$item)){
                $str=str_replace($item,'T',$str).'Z';
                if($item == ' 下午 ' or $item == ' 晚上 ' ){
                    $temp=substr($str,11,2)+12;
                    $str[11]=strval($temp)[0];
                    $str[12]=strval($temp)[1];
                }
                elseif ($item == ' 凌晨 12'){
                    $str[11]='0';
                    $str[12]='0';
                }
                break;
            }
        }
        return $str;
    }

}
