<?php

namespace App\Http\Controllers\Metrics\Wizard;

use App\Models\Resource;
use Illuminate\Http\Request;
use App\Services\ChartService;
use App\Services\MetricService;
use App\Http\Controllers\Controller;
use App\Services\DataConnectionService;
use App\Exceptions\SystemErrorException;
use App\Http\Requests\Metrics\SettingStepRequest;
use App\Http\Requests\Metrics\SettingStepUpdateRequest;

class SettingStepController extends Controller
{
    public $metricService;
    public function __construct(MetricService $metricService)
    {
        $this->metricService = $metricService;
    }

    public function store(SettingStepRequest $request)
    {
        $this->checkDataConnection($request);

        $this->metricService->storeSettingStep($request);

        return response()->json([
            'success'
        ]);
    }


    private function checkDataConnection($request){
        if(!(new DataConnectionService())
        ->getConnection(
            isset($request->connection)
            ? $request->connection
            : 'default'
        )){
            throw SystemErrorException::withMessages(
                ["error" =>"There is a problem with the chosen data connection."]
            );
        }
    }

    public function update(SettingStepUpdateRequest $request, Resource $metric)
    {
        $this->metricService->updateSettingStep($request, $metric);

        return response()->json([
            'success'
        ]);
    }
}
