<?php

namespace Tobuli\Helpers\Alerts;

use Tobuli\Entities\Device;
use Tobuli\Entities\Event;

class IdleDurationAlertCheck extends AlertCheck
{
    public function checkEvents($position, $prevPosition)
    {
        if ( ! $this->check())
            return null;

        $event = $this->getEvent();

        $duration = round($this->device->getIdleDuration() / 60);

        $event->type = 'idle_duration';
        $event->message = '';

        $event->additional = array_merge($event->additional ? $event->additional : [], [
            'idle_duration' => $duration
        ]);

        return [$event];
    }

    public function check()
    {
        if ( $this->alert->idle_duration < 1 )
            return false;

        $duration = round($this->device->getIdleDuration() / 60);

        if ($duration < $this->alert->idle_duration )
            return false;

        if ($this->device->getTimeoutStatus() == Device::STATUS_OFFLINE)
            return false;

        $position = $this->getPosition();

        if ( ! $position)
            return false;

        if ( ! $this->checkAlertPosition($position))
            return false;

        $check_at = max($this->device->traccar->moved_at, $this->device->traccar->engine_off_at);

        if (Event::where('user_id', $this->alert->user_id)
            ->where('alert_id', $this->alert->id)
            ->where('device_id', $this->device->id)
            ->where('type', 'idle_duration')
            ->where('created_at', '>=', $check_at)
            ->first(['id']))
            return false;

        return true;
    }

    public function getPosition()
    {
        $position = $this->device->positionTraccar();

        if ( ! $position)
            return null;

        $position->time = date('Y-m-d H:i:s');

        return $position;
    }
}