<?php namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;

use Carbon\Carbon;
use Facades\GeoLocation;
use Facades\Repositories\DeviceRepo;
use Tobuli\Helpers\GeoLocation\Location;
use Tobuli\Entities\File\DeviceCameraMedia;
use Illuminate\Support\Facades\File;
use Tobuli\History\DeviceHistory;

class DeviceWidgetsController extends Controller
{

    public function location($device_id)
    {
        $device = DeviceRepo::find($device_id);

        $this->checkException('devices', 'show', $device);

        try {
            $location = GeoLocation::byCoordinates($device->lat, $device->lng);
        } catch (\Exception $e) {
            $location = null;
        }

        return view('front::Widgets.location')->with([
            'location' => $location ? $location->toArray() : null
        ]);
    }

    public function cameras($device_id)
    {
        $device = DeviceRepo::find($device_id);

        $this->checkException('devices', 'show', $device);

        $images = [];
        $cameras = $device->getWidgetCameras();

        foreach ($cameras as $camera) {
            $image = DeviceCameraMedia::setEntity($camera)->findLatest();

            if ($image) {
                $images[$camera->id] = [
                    'camera_name' => $camera->name,
                    'image' => $image,
                    'device_id' => $camera->device_id,
                ];
            }
        }

        return view('front::Widgets.camera')->with([
            'images' => $images,
        ]);
    }

    public function image($device_id)
    {
        $device = DeviceRepo::find($device_id);

        $this->checkException('devices', 'show', $device);

        $image = $device->image;

        return view('front::Widgets.image')->with([
            'device' => $device,
            'image' => $image ? url($image) : null,
        ]);
    }

    public function fuelGraph($device_id)
    {
        $device = DeviceRepo::find($device_id);

        $this->checkException('devices', 'show', $device);

        try {
            $data = $this->sensorsData($device, ['fuel_tank', 'fuel_tank_calibration'], Carbon::now()->subDay(1), Carbon::now());
        } catch (\Exception $e) {
            $error = $e->getMessage();
        }

        return view('front::Widgets.fuel_graph')->with([
            'data'  => empty($data) ? null : $data,
            'error' => empty($error) ? null : $error
        ]);
    }

    private function sensorsData($device, $types, $from, $to) {
        $sensors = $device->sensors->filter(function($sensor) use ($types) {
            return in_array($sensor->type, $types);
        });

        if ($sensors->isEmpty())
            throw new \Exception( dontExist('front.sensor') );

        $history = new DeviceHistory($device);
        $history->setSensors($sensors);
        $history->setRange($from, $to);
        $history->registerActions([]);
        $history->get();

        return $history->getSensorsData();
    }
}
