<?php

namespace App\Repositories;

use App\Models\Module;
use App\Models\Resource;
use Illuminate\Support\Str;
use App\Models\ResourcePermission;
use Illuminate\Support\Facades\DB;
use App\Models\ResourceConfiguration;

class MetricRepository
{
    public function store()
    {
        $session = session()->get('metric_session_wizard_configuration');
        DB::transaction(function () use ($session) {
            $resource = Resource::create([
                'name'                => $session["name"],
                'url'                 => $this->getUrl(Str::slug($session["name"], '_')),
                'access_control_type' => ucfirst($session["security_type"]),
                'module_id'           => $this->getMetricModuleId(),
                'category_id'         => intval($session["category"]),
                'resource_creator'    => auth()->id(),
                'data_connection_id'  => strtolower($session["connection"]) != "default" ? intval($session["connection"]) : null,
                'widget_size'         => $this->widgetSize("quarter"),
                'metric_color'        => !empty($session["metric_color"]) ? $session["metric_color"] : null,
                'info_box_icon'       => isset($session["info_box_icon"]) ? $session["info_box_icon"] : null
            ]);

            if (!is_null($session["groups"])) {

                if (auth()->user()->isAdminOrOwner()) {

                    foreach ($session["groups"] as $group) {
                        ResourcePermission::create([
                            'group_id'    => $group,
                            'resource_id' => $resource->id,
                            'can_view'    => true
                        ]);
                    }

                } else {
                    ResourcePermission::create([
                        'group_id'    => auth()->user()->group->group_ID,
                        'resource_id' => $resource->id,
                        'can_view'    => true
                    ]);

                }

            }

            ResourceConfiguration::create([
                'Resource_id'         => $resource->id,
                'Json_configurations' => $session,
                'chart_type'          => $session["metric_type"]
            ]);
            session()->forget('metric_session_wizard_configuration');

        });
    }

    public function update($metric)
    {
        $session = session()->get('metric_session_wizard_configuration');

        DB::transaction(function () use ($session, $metric) {

            $resource = $metric->update([
                'name'                => isset($session["name"]) ? $session["name"] : $metric->name,
                'url'                 => isset($session["name"]) ? $this->getUrl(Str::slug($session["name"], '_')) : $metric->url,
                'access_control_type' => isset($session["security_type"]) ? ucfirst($session["security_type"]) : $metric->access_control_type,
                'module_id'           => $this->getMetricModuleId(),
                'category_id'         => isset($session["category"]) ? intval($session["category"]) : $metric->category_id,
                'widget_size'         => $this->widgetSize("quarter"),
                'metric_color'        => $this->getUpdatedMetricColor($session, $metric),
                'info_box_icon'       => $this->getUpdatedInfoBoxIcon($session, $metric)

            ]);

            if (isset($session["groups"])) {

                ResourcePermission::where('resource_id', $metric->id)->delete();

                if (auth()->user()->isAdminOrOwner()) {

                    foreach ($session["groups"] as $group) {

                        ResourcePermission::create([
                            'group_id'    => $group,
                            'resource_id' => $metric->id,
                            'can_view'    => true
                        ]);

                    }

                } else {
                    ResourcePermission::create([
                        'group_id'    => auth()->user()->group->group_ID,
                        'resource_id' => $metric->id,
                        'can_view'    => true
                    ]);

                }

            }

            ResourceConfiguration::updateOrCreate(
                ['Resource_id' => $metric->id],
                [
                    'Json_configurations' => $this->getUpdatedSession($session, $metric),
                    'chart_type'          => isset($session["metric_type"]) ? $session["metric_type"] : $metric->getResourceConfiguration("metric_type")
                ]
            );
            session()->forget('metric_session_wizard_configuration');
        });
    }

    private function getMetricModuleId()
    {
        return Module::where('name', 'KPIs / Metrics')->first()->id;
    }

    private function widgetSize($size)
    {

        switch ($size) {
            case 'full':
                return 1;
                break;
            case 'half':
                return 2;
                break;
            case 'quarter':
                return 3;
                break;
        }

    }

    private function getUrl($metricName)
    {
        return substr(getBaseUrl(), -1) == "/"
        ? getBaseUrl() . "srm_metrics/" . $metricName
        : getBaseUrl() . "/srm_metrics/" . $metricName;
    }

    private function getUpdatedSession($session, $metric)
    {
        return array_merge($metric->configurations->Json_configurations, $session);
    }

    private function getUpdatedMetricColor($session, $metric)
    {

        if (!empty($session["metric_color"])) {
            return $session["metric_color"];
        } elseif (!empty($metric->metric_color)) {
            return $metric->metric_color;
        } else {
            return null;
        }

    }

    private function getUpdatedInfoBoxIcon($session, $metric)
    {

        if (!empty($session["info_box_icon"])) {
            return $session["info_box_icon"];
        } elseif (!empty($metric->info_box_icon)) {
            return $metric->info_box_icon;
        } else {
            return null;
        }

    }

}
