<?php

include_once "server/lib/mod_dbm/package.dbm.php";
include_once("server/class/GeoUtils.php");
include_once("server/class/Location.php");


/*
 * ROMAN DIGITAL - Autor: Américo Patetta
 */

/**
 * Description of LocationManager
 *
 * @author pc
 */
class LocationManager {
    
    private $dao;
    
    function __construct($dao=null){
        if($dao==null){
            $dao = new dbObject();
        }
        $this->dao = $dao;
    }
        
    function getCloseLocation($lat, $lng, $autoInsert = false): Location{
        
        $locatioQuery = sprintf("SELECT l.* FROM locations l ORDER BY  POW(l.lat-%s,2)+POW(l.lng-%s,2) LIMIT 0,1",$lat,$lng);
        $closer = $this->dao->fetchQuery($locatioQuery);
        if(is_array($closer) && count($closer) && GeoUtils::getTheDistance($lat, $lng, $closer[0]['lat'], $closer[0]['lng']) < LOCATION_DISTANCE_TH){
            $location = new Location($closer[0]['location_id']);
        } else {
            if($autoInsert){
                $location = new Location();
                $location->create($lat, $lng);
                $location->persist();
                
            } else {
                $location = null;
            }
        }
        return $location;
    }
    
    function createLocation($lat,$lng){
        $location = new Location();
    }
    
}


