<?php

namespace App\Jobs;

use Carbon\Carbon;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Tobuli\Entities\Device;
use Tobuli\Entities\Event;
use Formatter;
use Tobuli\Entities\SendQueue;
use Tobuli\Entities\User;

class ConfirmFuelLevelChange extends Job implements SelfHandling, ShouldQueue
{
    use InteractsWithQueue, SerializesModels;

    const SECONDS_GAP = 300;
    const PERCENTAGE_CHANGE_THRESHOLD = 15;

    private $event_data;
    private $time;
    private $device;
    private $user;

    public function __construct($time, $event_data)
    {
        $this->time = $time;
        $this->event_data = $event_data;
        $this->device = Device::find($this->event_data['device_id']);
        $this->user = User::find($this->event_data['user_id']);

        Formatter::byUser($this->user);
    }

    public function handle()
    {
        $positions = $this->device->positions()
            ->whereBetween('time', [
                Carbon::parse($this->time)->subSeconds(self::SECONDS_GAP),
                Carbon::parse($this->time)->addSeconds(self::SECONDS_GAP)
            ])
            ->orderBy('time', 'asc')
            ->orderBy('id', 'asc')
            ->get();

        if ($positions->count() < 2)
            return;

        try {
            $change = getFuelDifference($this->device, $positions);
        } catch (\Exception $exception) {
            return;
        }

        $percent = $change['percent'];
        $difference = $change['difference'];

        if (abs($percent) < self::PERCENTAGE_CHANGE_THRESHOLD)
            return;

        $this->event_data = array_merge($this->event_data, [
            'type'       => $percent > 0 ? Event::TYPE_FUEL_FILL : Event::TYPE_FUEL_THEFT,
            'message'    => $percent > 0 ? trans('front.fuel_fillings') : trans('front.fuel_thefts'),
            'additional' => [
                'difference' => round(abs($difference))
            ]
        ]);

        $event = Event::create($this->event_data);

        SendQueue::create([
            'user_id'   => $event->user_id,
            'type'      => $event->type,
            'data'      => $event,
            'channels'  => $this->event_data['channels']
        ]);
    }
}