<?php

namespace App\Controller\Api;

use App\Controller\Api\AppController;
use App\Model\Entity\Weather;
use App\Model\Table\WeathersTable;
use Aura\Intl\Exception;
use Cake\I18n\Date;
use Cake\I18n\Time;
use DateTime;

/**
 * Weather Controller
 *
 * @property \App\Model\Table\WeathersTable $Weather
 *
 * @method \App\Model\Entity\Weather[] paginate($object = null, array $settings = [])
 */
class WeathersController extends AppController
{
    use \Crud\Controller\ControllerTrait;

    public function initialize()
    {
        parent::initialize();
        $this->Crud->enable(['average']);
        // print_r($this->Crud);
        $this->Auth->allow(['index', 'average']);
    }

    public function index()
    {
        /*
         * REQUEST TYPE: GET
         * Headers: Accept -> application/vnd.api+json (IMPORTANT!!!)
         */
        // Query parameters handle
        $this->Crud->on('beforePaginate', function (\Cake\Event\Event $event) {
            $params = $this->request->getQueryParams();
            $query = $event->getSubject()->query;

            if (isset($params['date'])) {
                $date = $params['date'];
                $startTime = new DateTime($date);
                $endTime = new DateTime($date);
                $startTime->setTime(0, 0, 0);
                $endTime->setTime(23, 59, 59);

                if (isset($params['time'])) {
                    // If time query string param is set, get average values from + - 30minutes
                    $queryTime = new Time($params['time']);
                    $startTime->setTime($queryTime->hour, $queryTime->minute, $queryTime->second);
                    $endTime->setTime($queryTime->hour, $queryTime->minute, $queryTime->second);
                }

                $query->find('betweenDates', [
                    'filterStartDate' => $startTime->format("Y-m-d H:i:s"),
                    'filterEndDate' => $endTime->format("Y-m-d H:i:s")]);
            };
        });
        // Execute json api request
        return $this->Crud->execute();
    }

    /*
    * REQUEST TYPE: GET
    * Headers: Accept -> application/vnd.api+json (IMPORTANT!!!)
    */
    public function average()
    {
        $this->Crud->on('beforePaginate', function (\Cake\Event\Event $event) {
            $params = $this->request->getQueryParams();
            $query = $event->getSubject()->query;

            if (!isset($params['date'])) {
                $event->stopPropagation();
                throw new \BadMethodCallException("Parameter date not set!", 500);
            }

            $date = $params['date'];
            $startTime = new DateTime($date);
            $endTime = new DateTime($date);
            $startTime->setTime(0, 0, 0);
            $endTime->setTime(23, 59, 59);

            if (isset($params['time'])) {
                // If time query string param is set, get average values from + - 30minutes
                $queryTime = new Time($params['time']);
                $startTime->setTime($queryTime->hour, $queryTime->minute, $queryTime->second);
                $endTime->setTime($queryTime->hour, $queryTime->minute, $queryTime->second);
                $interval = new \DateInterval("PT30M");
                $startTime->sub($interval);
                $endTime->add($interval);
            }

            // Get the average values
            $query->select([
                'avg_temp' => $query->func()->avg('teplota'),
                'avg_pres' => $query->func()->avg('tlak'),
                'avg_uv' => $query->func()->avg('uv'),
                'avg_hum' => $query->func()->avg('vlhkost'),
                'avg_water' => $query->func()->avg('voda'),
            ])->find('betweenDates', [
                'filterStartDate' => $startTime->format("Y-m-d H:i:s"),
                'filterEndDate' => $endTime->format("Y-m-d H:i:s")]);
        });
        return $this->Crud->execute();
    }

    public $paginate = [
        'page' => 1,
        'limit' => 10,
        'maxLimit' => 100
    ];

}
