<?php

namespace Tobuli\Reports\Reports;

use Facades\Repositories\EventRepo;
use Formatter;
use Carbon\Carbon;
use Tobuli\Reports\DeviceReport;

class EventDeviceReport extends DeviceReport
{
    protected $offline_timeout;

    const TYPE_ID = 8;

    public function typeID()
    {
        return self::TYPE_ID;
    }

    public function title()
    {
        return trans('front.events');
    }

    protected function generate()
    {
        foreach ($this->devices as $device)
        {
            $this->items[] = $this->generateDevice($device);
        }
    }

    protected function generateDevice($device)
    {
        $events = EventRepo::getBetween($this->user->id, $device->id, $this->date_from, $this->date_to);

        if (empty($events))
            return [
                'meta' => $this->getDeviceMeta($device),
                'error' => trans('front.nothing_found_request')
            ];

        $totals = [];

        foreach ($events as & $event) {
            //$event['message']  = parseEventMessage($event['message'], $event['type']);
            $event['time']     = Formatter::time()->human($event['time']);
            $event['location'] = $this->getLocation((object)[
                'latitude' => $event['latitude'],
                'longitude' => $event['longitude']
            ]);

            if (empty($totals[$event['message']]))
                $totals[$event['message']] = [
                    'title' => trans('front.total') . ' ' . $event['message'],
                    'value' => 0,
                ];

            $totals[$event['message']]['value']++;
        }

        return [
            'meta' => $this->getDeviceMeta($device),
            'table' => [
                'rows' => $events
            ],
            'totals' => $totals
        ];
    }
}