<?php

namespace App;

use App\Http\Controllers\AutomatickeBanovaniController;
use Eloquent;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Carbon\Carbon;

/**
 * App\Mqtt_data_request
 *
 * @property int $idRequest
 * @property string|null $topic
 * @property float|null $hodnota
 * @property string|null $vlozeny
 * @property int|null $vlozil
 * @method static Builder|Mqtt_data_request newModelQuery()
 * @method static Builder|Mqtt_data_request newQuery()
 * @method static Builder|Mqtt_data_request query()
 * @method static Builder|Mqtt_data_request whereHodnota($value)
 * @method static Builder|Mqtt_data_request whereIdRequest($value)
 * @method static Builder|Mqtt_data_request whereTopic($value)
 * @method static Builder|Mqtt_data_request whereVlozeny($value)
 * @method static Builder|Mqtt_data_request whereVlozil($value)
 * @mixin Eloquent
 * @property int $idmqtt_data_request
 * @property int|null $id_stanice
 * @property string|null $data
 * @method static Builder|Mqtt_data_request whereData($value)
 * @method static Builder|Mqtt_data_request whereIdStanice($value)
 * @method static Builder|Mqtt_data_request whereIdmqttDataRequest($value)
 */
class Mqtt_data_request extends Model
{
    protected $table = 'mqtt_data_request';
    protected $primaryKey = 'idmqtt_data_request';
    protected $fillable = ['topic','id_stanice','data','vlozeny', 'vlozil'];
    public $timestamps = false;

    /**
     * @param $idStanice
     * @return Collection
     */
    public static function getData($idStanice): Collection
    {
        return self::where([
                                ['id_stanice','=',$idStanice],
                                ['vlozeny','>=',date('Y-m-d H:i:s', (strtotime(date(self::whereIdStanice($idStanice)->max('vlozeny'))) - 2))],
                            ])
                        ->get();
    }

    public static function getDataGraf($idStanice,$od = null, $do = null)
    {
        if($od === null)
        {
            $od = '0000-00-00 00:00:00';
        }

        return self::where([
            ['id_stanice','=',$idStanice],
            ['vlozeny','>=', $od],
            ['vlozeny','<=', $do],
        ])->get();
    }

    public static function getCountMsg(AutomatickeBanovani $banovani)
    {
        return self::where([
            ['id_stanice', '=',$banovani->id_stanice],
            ['vlozeny','>=',Carbon::now()->subMinutes($banovani->pocet_minut)->toDateTimeString()]
        ])->count();
    }

    public static function getDataLast($idStanice)
    {
        return self::where(['id_stanice'=>$idStanice])->orderByDesc('vlozeny')->limit(1)->get(['vlozeny','id_stanice']);
    }
}
