<?php

namespace Tobuli\Helpers\Alerts;

use Tobuli\Entities\Checklist;
use Tobuli\Entities\ChecklistTemplate;
use Tobuli\Entities\Device;
use Tobuli\Entities\Event;

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

        $event = $this->getEvent();

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

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

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

        return [$event];
    }

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

        if (! $position) {
            return false;
        }

        $alertDuration = $this->alert->ignition_duration * 60; //in seconds

        if ($alertDuration < 1) {
            return false;
        }

        $duration = $this->device->getIgnitionDuration();

        if ($duration < $alertDuration) {
            return false;
        }

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

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

        if ($this->alert->pre_start_checklist_only) {
            if (! Checklist::whereIn('service_id', $this->device->services()->lists('id'))
                ->incomplete()
                ->type(ChecklistTemplate::TYPE_PRE_START)
                ->count()
            ) {
                return false;
            }
        }

        if (Event::where('user_id', $this->alert->user_id)
            ->where('alert_id', $this->alert->id)
            ->where('device_id', $this->device->id)
            ->where('type', 'ignition_duration')
            ->where('time', '>=', $this->device->traccar->engine_off_at)
            ->first(['id'])
        ) {
            return false;
        }

        return true;
    }
}
