<?php

namespace App\Http\Controllers;

use App\{Mqtt_data_request, VizitkaDefine, WuDefinicePristupu};
use Illuminate\Support\Facades\Http;

class ExportToWUController extends Controller
{

    private const PODPOROVANE_VELICINY = ['Teplota','Vlhkost', 'Tlak', 'UV'];

    /**
     * @param $idStanice
     */

    public function requestToWU($idStanice = null): void
    {
        if($idStanice === null)
        {
            foreach (WuDefinicePristupu::all() as $poradi => $dataPristupu)
            {
                $this->requestToWUSpecificID($dataPristupu->id_stanice);
            }
        }
        else
        {
            $this->requestToWUSpecificID($idStanice);
        }

    }


    private function requestToWUSpecificID($idStanice): string
    {

        /**
         * 1) vytahnu autentizaci
         * 2) najdu všechny data ze stanice od posledniho exportu
         * 3) updadutu autentizaci timestamp
         * 4)procyklim, převedu a odesilam jednotlive requesty
         */

        $dataConnection = WuDefinicePristupu::whereIdStanice($idStanice)->get()->toArray()[0];
        if(!isset($dataConnection))
        {
            return 'fail';
        }

        foreach (VizitkaDefine::getModalSelect($idStanice) as $id => $data)
        {
            if(isset($data['nazev']))
            {
                $veliciny[$data['sloupec_velicina']] = $id ;
                $nazevAsloupec[$data['sloupec_velicina']] = $data['nazev'];
                $velicinyAjednotky[$id]['sloupec_velicina'] = $data['nazev'];
                $velicinyAjednotky[$id]['jednotka'] = $data['jednotka'];
            }
        }
        $dataStanice = Mqtt_data_request::getDataGraf($idStanice,$dataConnection['last_export'],date('Y-m-d H:i:s'));
        WuDefinicePristupu::updateExportTime($idStanice);
        foreach ($dataStanice as $id => $dataProExport)
        {
            $dataExport['vlozeny']=$dataProExport->vlozeny;
            foreach (json_decode($dataProExport->data) as $idD => $dataD)
            {
                if(isset($nazevAsloupec[$dataD->name]) && in_array($nazevAsloupec[$dataD->name], self::PODPOROVANE_VELICINY) && array_key_exists($dataD->name, $veliciny))
                {
                    if($velicinyAjednotky[$veliciny[$dataD->name]]['jednotka'] === '°C')
                    {
                        $dataExport[$nazevAsloupec[$dataD->name]] = $this->celsiusToFahrenheit((float)$dataD->value);
                    }
                    elseif ($velicinyAjednotky[$veliciny[$dataD->name]]['jednotka'] === 'hPa')
                    {
                        $dataExport[$nazevAsloupec[$dataD->name]]  = $this->tlakHPaToIN((float)$dataD->value);
                    }
                    else
                    {
                        $dataExport[$nazevAsloupec[$dataD->name]]  = (float)$dataD->value;
                    }
                }
            }
            $this->doRequest($dataExport,$dataConnection);
            $dataExport = [];
        }

        return 'ok';
    }


    private function doRequest($dataExport,$dataConnection): void
    {

        $parametry = [];
        $parametry['ID'] =  $dataConnection['id_wu_station'];
        $parametry['PASSWORD']  = $dataConnection['pass'];
        $parametry['dateutc']  = $dataExport['vlozeny'];
       // $parametry['dateutc']  = '2020-04-17 08:20:20';
        $parametry['action']  = 'actionraw';
        if(isset($dataExport['Teplota']))
        {
            $parametry['tempf'] = $dataExport['Teplota'];
            //$parametry['tempf'] = 69.69;
        }
        if(isset($dataExport['Vlhkost']))
        {
            $parametry['humidity'] = $dataExport['Vlhkost'];
        }
        if(isset($dataExport['Tlak']))
        {
            $parametry['baromin'] = $dataExport['Tlak'];
        }
        if(isset($dataExport['UV']))
        {
            $parametry['uv'] = $dataExport['UV'];
        }
        // undefine index
        Http::get('https://rtupdate.wunderground.com/weatherstation/updateweatherstation.php', $parametry);
        //dump( $parametry['dateutc']);
    }

    public function celsiusToFahrenheit(float $celsius) : float
    {
        $number =  $celsius * 1.8 + 32;
        return number_format((float)$number, 2, '.', '');
    }

    public function tlakHPaToIN(float $tlak): float
    {
        $number =  $tlak/33.864;
        return number_format($number, 2, '.', '');
    }
}
