<?php

namespace App\Http\Controllers;

use App\Mqtt_data_request;
use App\VizitkaDefine;
use Carbon\Carbon;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ModalController extends Controller
{

    private $timeStamp = [];
    private $hodnotyKZprumerovani = [];
    private $velicina;
    private $sloupecVelicina;
    private $jednotka;
    private $hodnoty = [];
    private $idStanice;
    private $od;
    private $do;

    /**
     * @param $idStanice
     * @param string $nazevVeliciny
     * @param $sloupecVelicina
     * @param string $jednotka
     * @param string $četnost
     * @param null $od
     * @param null $do
     * @return array
     */
    private function vytvorDataProGraf($idStanice, $nazevVeliciny = 'Teplota', $sloupecVelicina='', $jednotka = '', $cetnost = 'day', $od=null, $do=null): array
    {
        if($do)
        {
            $this->do = $do. ' 23:59:59';
        }
        if($do === null)
        {
            $this->do= date('Y-m-d H:i:s');
        }

        $this->od = $od;
        $this->idStanice = $idStanice;
        $this->velicina = $nazevVeliciny;
        $this->sloupecVelicina = $sloupecVelicina;
        $this->jednotka = $jednotka;
        $data = Mqtt_data_request::getDataGraf($idStanice, $this->od, $this->do);
        if($this->od === null)
        {
            $this->od = 'Od počátku věků';
        }
        else
        {
            $this->od = Carbon::parse($this->od)->format('d. m. Y H:i:s');
        }
        $stareVlozeni = '0000-00-00 00:00:00';
        foreach ($data as $id => $dataStanice)
        {
            if($dataStanice->vlozeny > $stareVlozeni)
            {
                if($cetnost === 'day')
                {
                    $stareVlozeni = Carbon::parse($dataStanice->vlozeny)->addDay()->format('Y-m-d H:i:s');
                    $this->timeStamp[] = Carbon::parse($dataStanice->vlozeny)->format('Y-m-d');
                }
                elseif($cetnost === 'hour')
                {
                    $stareVlozeni = Carbon::parse($dataStanice->vlozeny)->addHour()->format('Y-m-d H:i:s');
                    $this->timeStamp[] = Carbon::parse($dataStanice->vlozeny)->format('Y-m-d H:i');
                }
                elseif($cetnost === 'week')
                {
                    $stareVlozeni = Carbon::parse($dataStanice->vlozeny)->addWeek()->format('Y-m-d H:i:s');
                    $this->timeStamp[] = Carbon::parse($dataStanice->vlozeny)->format('Y-m-d');
                }
                elseif($cetnost === 'month')
                {
                    $stareVlozeni = Carbon::parse($dataStanice->vlozeny)->addMonth()->format('Y-m-d H:i:s');
                    $this->timeStamp[] = Carbon::parse($dataStanice->vlozeny)->format('Y-m');
                }
                else
                {
                    $this->timeStamp[] = Carbon::parse($dataStanice->vlozeny)->format('Y-m-d H:i:s');
                }

            }
            else
            {
                $this->nastavDataKZprumerovani(json_decode($dataStanice->data));
                continue;
            }

            if(!empty($this->hodnotyKZprumerovani))
            {
                $this->hodnoty[] = (float)$this->zprumerujData();
            }
            else
            {
                foreach (json_decode($dataStanice->data) as $idD => $dataD)
                {
                    if($dataD->name === $this->sloupecVelicina)
                    {
                        $this->hodnoty[] = (float)$dataD->value;
                    }
                }
            }
        }

        return $this->getDataJsonDB();
    }

    private function zprumerujData()
    {
        $soucet = 0;
        foreach ($this->hodnotyKZprumerovani as $id => $hodnoty)
        {
            $soucet += (float)$hodnoty;
        }

        $number = $soucet/count($this->hodnotyKZprumerovani);
        return number_format((float)$number, 2, '.', '');

    }

    private function nastavDataKZprumerovani($data): void
    {
        foreach ($data as $idD => $dataD)
        {
            if($dataD->name === $this->velicina )
            {
                $this->hodnotyKZprumerovani[] = (float)$dataD->value;
            }
        }
    }

    private function getDataJsonDB(): array
    {
        return [
            'title' => [
                'text' => 'Hodnoty čidla ID:' .$this->idStanice
            ],
            'subtitle' => [
                'text' => 'Za období: '.$this->od.' - '.Carbon::parse($this->do)->format('d. m. Y H:i:s')
            ],
            'yAxis' => [
                'title' => ['text' => $this->velicina.' ['.$this->jednotka.']']
            ],
            'xAxis' => [
                'categories' => $this->timeStamp
            ],
            'legend'=> [
                'layout' => 'vertikal',
                'align' => 'right',
                'verticalAlign' => 'middle'
            ],
            'series'=> [
                [
                    'name' => $this->velicina,
                    'data' => $this->hodnoty,
                ]
            ],
            'chart'=> [
                'type' => 'line',
                'renderTo' => 'chart1'
            ],
            'colors'=> ['#0c2959'],
            'tooltip'=> [
                            'crosshairs' => [true,true]
                        ],
            'credits'=>false
        ];
    }


    /**
     * @param $request
     * @return JsonResponse
     */
    protected function getDataJson($request): JsonResponse
    {
        return response()->json($this->vytvorDataProGraf($request));
    }

    /**
     * @param Request $request
     * @return Application|Factory|View
     */
    protected function getDataOvladani(Request $request)
    {
        $data = $request->all();
        $dataSelect = VizitkaDefine::getModalSelect($data['id']);
        return view('ovladaniGrafu',['data' => $dataSelect, 'id_stanice' => $data['id']]);
    }

    public function getRefreshGraf(Request $request)
    {
        $data = $request->all();
        if(!isset( $data['form']))
        {
            $dataSelect = VizitkaDefine::getModalSelect($data['id']);
            if(isset($dataSelect[0]['nazev']))
            {
                $a = [
                        [
                            'value' => $dataSelect[0]['nazev'],
                            'jednotka' => $dataSelect[0]['jednotka'],
                        ]
                    ];
            }
            else
            {
                $a = [
                        [
                            'value' => $dataSelect[0]['sloupec_velicina'],
                            'jednotka' => '-',
                        ]
                    ];
            }

            return response()->json($this->vytvorDataProGraf($data['id'],$a[0]['value'],$dataSelect[0]['sloupec_velicina'], $a[0]['jednotka']));
        }
        $a = $data['form'];
        if($a[0]['value'])
        {
            if(explode('_',$a[0]['value']))
            {
                $nazevAjednotka = explode('_',$a[0]['value']);
            }
            if(!isset($nazevAjednotka[2]))
            {
                $nazevAjednotka[1] = $a[0]['value'];
                $nazevAjednotka[2] = '-';
            }
        }
        /** @var string $nazevAjednotka */
        return response()->json($this->vytvorDataProGraf($data['id'],$nazevAjednotka[0],$nazevAjednotka[1],$nazevAjednotka[2],$a[1]['value'],$a[2]['value'],$a[3]['value']));
    }
}
