<?php

namespace App\Http\Controllers;

use Illuminate\Routing\Controller as BaseController;
use App\Models\Weather as Weather;
use Illuminate\Http\Request;

class WeatherData extends BaseController
{
	public function gui()
	{
		return view('weather.gui');
	}
	
	public function fetch (Request $request, $location)
	{
		return response()->json(Weather::where('name', $location)->latest()->get()->toArray());
	}
	
    public function syncronize()
    {
        $locations['Berlin Mitte'] = [
            'lat' => '52.520008', 
            'lon' => '13.404954'
        ];
        
        $locations['Berlin Friedrichshain'] = [
        		'lat' => '52.515816',
        		'lon' => '13.454293'
        ];
        
        foreach($locations as $name => $location)
        {
        	echo "Fetching data for: " . $name . PHP_EOL;
        	if($openWeatherMapData = $this->getWeatherData($location['lat'], $location['lon']))
        	{
	        	$weather = new Weather();
	        	$weather->name = $name;
	        	$weather->latitude = $location['lat'];
	        	$weather->longitude = $location['lon'];
	        	$weather->temp = $openWeatherMapData['main']['temp'];
	        	$weather->temp_min = $openWeatherMapData['main']['temp_min'];
	        	$weather->temp_max = $openWeatherMapData['main']['temp_max'];
	        	$weather->pressure = $openWeatherMapData['main']['pressure'];
	        	$weather->humidity = $openWeatherMapData['main']['humidity'];
	        	$weather->save();
	        	echo "Weather data: " . print_r($weather->toArray(), true);
	        	
	        	echo "Saving data for: " . $name . PHP_EOL;
        	}else{
        		echo '<pre>Error processing weather data for: ' . $name . PHP_EOL . '</pre>';
        	}
        }
        
        echo '</pre>';
    }
    
    public function getWeatherData($lat, $lon)
    {
    	try{
    		$datajson = file_get_contents("https://api.openweathermap.org/data/2.5/weather?lat=$lat&lon=$lat&appid=bf65d8b174418831a16055a19f50144f&units=metric");
    	}catch (\Exception $error)
    	{
    		return false;
    	}
    	
    	return json_decode($datajson, true);
    }
}
