<?php

namespace App\Http\Controllers\Charts\Wizard;

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

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

    public function store(SettingStepRequest $request)
    {

        $this->checkDataConnection($request);
        $this->chartService->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 $chart)
    {
        $this->chartService->updateSettingStep($request, $chart);

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