<?php

namespace App\Repositories;

use App\Models\Resource;
use App\Models\DashboardWidget;

class DashboardWidgetRepository
{
    public function store($request, $dashboard)
    {
        DashboardWidget::create(
            [
                'resource_id'  => $this->getResourceId($request),
                'report_lists' => $this->getReportLists($request),
                'title'        => $this->getWidgetTitle($request),
                'dashboard_id' => $dashboard->id

            ]
        );
    }

    public function update($request, $dashboard, $widget)
    {
        $widget->update([
            'report_lists' => $this->getReportLists($request),
            'widget_title' => $this->getWidgetTitle($request)
        ]);
    }

    public function destroy($dashboard, $widget)
    {
        $widget->delete();
    }

    private function getResourceId($request)
    {
        $resourceType = Resource::where('id', $request->resource)->first();

        if (isset($resourceType) && $resourceType->getResourceType() == "Blank Reports") {
            return null;
        } else {
            return $request->resource;
        }

    }

    private function getReportLists($request)
    {
        $resourceType = Resource::where('id', $request->resource)->first();

        if (isset($resourceType) && $resourceType->getResourceType() != "Blank Reports") {
            return null;
        }

        $resourcesArray = [];

        if (is_array($request->resource)) {

            foreach ($request->resource as $resource) {
                $resourcesArray[] = $this->buildResourceArray($resource);
            }

        }

        return $resourcesArray;
    }

    private function buildResourceArray($resourceId)
    {
        $resource = Resource::where('id', $resourceId)->first();

        return [
            'id'    => $resource->id,
            'name'  => $resource->name,
            'title' => $resource->getResourceConfiguration('title'),
            'url'   => $resource->url
        ];
    }

    private function getWidgetTitle($request)
    {
        $resourceType = Resource::where('id', $request->resource)->first();

        if (isset($resourceType) && $resourceType->getResourceType() != "Blank Reports") {
            return null;
        } else {
            return $request->title;
        }

    }

}
