<?php

class RouteApi extends Api
{
    public $apiName = 'route';

    public function indexAction()
    {
        return $this->response(
            array(
                'error' => 'Data not found'
            ), 404);
    }

    /**
     * Method GET
     * Get single record (by id)
     * http://DOMAIN/remove/1
     * @return string
     */
    public function viewAction()
    {
        //id must be the first parameter after /remove/x
        return $this->response(
            array(
                'error'=> 'Data not found'
            ), 404);
    }

    public function createAction()
    {
        $message = "Unexpected route error";

        $from = $this->requestParams["from"] ?? ",";
        $to = $this->requestParams["to"] ?? ",";
        $mode = $this->requestParams["mode"] ?? 'DRIVING';
        try {
            if(!is_array($from) || !is_array($to)){
                return $this->response(
                    array(
                        "error" => $message
                    ), 500);
            }
            $fromCoords = implode(',',$from);
            $toCoords = implode(',',$to); 
            list($res, $err) = RouteApi::route($fromCoords, $toCoords, $mode);
            
            if ($err==NULL && is_array($res) && isset($res["routes"]) && count($res["routes"])>0) {
                //$result["route_overlay"] = [];
                $result = [];
                foreach ($res["routes"] as $route) {
                    $result[] = RouteApi::processRoute($route);
                }
                
                return $this->response(array(
                        'routes' => $result,
                        'error' =>$err
                    )
                );
            } else {
                throw new Exception("Failed to get route");
            }
        } catch (Exception $e) {
            $message = $e->getMessage();
        }
        return $this->response(
            array(
                "error" => $message
            ), 500);
    }

    public function updateAction()
    {
        return $this->response(
            array(
                "error" => "Update error"
            ), 400);
    }

    public function deleteAction()
    {
        return $this->response(
            array(
                "error" => "Delete error"
            ), 500);
    }

    public function route($fromCoords, $toCoords, $mode='driving', $waypoints=[]) {
        syslog(LOG_WARNING,"Trip RouteApi::route($fromCoords, $toCoords, $mode, \$waypoints=[])");
        global $savvyext;
        $httpAuthToken = $savvyext->cfgReadChar('system.oauth2_token');
        $oauth2_url = $savvyext->cfgReadChar('system.oauth2_url'); 

        $data = http_build_query(
            array(
                'gps' => implode(",",array($fromCoords, $toCoords)),
                'mode' => $mode,
                'waypoints' => implode(",",$waypoints)
            )
        );
        //$data = "gps=".implode(",",array($fromCoords, $toCoords))."&mode=DRIVING";
        $url = $oauth2_url."route?" . $data;
        $opts = array(
            'http' => array(
                'method' => "GET",
                'timeout' => 60, /* 1 minute */
                'header'  => 
                    "Content-Type: text/plain\r\n" .
                    //"Accept: application/json\r\n" .
                    "Authorization: Server-Token ${httpAuthToken}\r\n",
            ),
            "ssl" => array(
              "verify_peer"=>false,
              "verify_peer_name"=>false,
            )
        );
        $context = stream_context_create($opts);
        $body = file_get_contents($url, false, $context);
       
        $route = json_decode($body,true);
        //var_dump($route["data"]);exit;
        if (is_array($route) && is_array($route["data"]) && !isset($route["error"])) {
            return array($route["data"], NULL);
        } else if (is_array($route) && isset($route["error"])) {
            $body = $route["error"];
        }
        return array(NULL, "Routing service call error: ".$body);
    }

    public function processRoute($route) {
        require_once('../common/Polyline.php');
        $result = [
            'distance' => NULL, 
            'duration' => NULL, 
            'overview_polyline' => $route["overview_polyline"],
            'bounds' => $route["bounds"]
        ];
        $distance = 0;
        $duration = 0;
        foreach ($route["legs"] as $leg) {
            $distance += $leg["distance"]["value"];
            $duration += $leg["duration"]["value"];
           
        }
        $result['distance'] = $distance;
        $result['duration'] = $duration;
        return $result;
    }
}
