<?php namespace Tobuli\Helpers\Dashboard\Blocks;

class DeviceActivityBlock extends Block
{
    protected function getName()
    {
        return 'device_activity';
    }

    protected function getContent()
    {
        $devices = $this->user->devices()->with(['traccar'])->get();

        if (empty($devices))
            return null;

        $offline_devices = $devices->filter(function ($device) {
            return $device->getTimeoutStatus() === $device::STATUS_OFFLINE;
        });

        $online_percentage = $this->calculateOnlinePercentage(
            $devices->count(),
            $offline_devices->count()
        );

        return [
            'online'  => round($online_percentage, 1),
            'offline' => round(100 - $online_percentage, 1),
        ];
    }

    private function calculateOnlinePercentage($device_count, $offline_count)
    {
        if (empty($device_count))
            return 0;

        return (($device_count - $offline_count) / $device_count) * 100;
    }
}