<?php

namespace App\Http\Controllers;

use App\Menu;
use App\MqttServerSet;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Auth;

class MqttServerSetController extends Controller
{
    public function index()
    {
        return view('NastaveniMqttServer.nastaveniMqtt', ['dataC' => MqttServerSet::all(),'menu' => Menu::getData()]);
    }

    public function add()
    {
        return view('NastaveniMqttServer.nastaveniMqttAdd', ['menu' => Menu::getData()]);
    }

    public function edit(MqttServerSet $idmqtt_server_set)
    {
        return view('NastaveniMqttServer.nastaveniMqttEdit',['dataC' => $idmqtt_server_set,'menu' => Menu::getData()]);
    }

    public function delete(MqttServerSet $idmqtt_server_set)
    {
        try
        {
            $idmqtt_server_set->delete();
        }
        catch (Exception $e)
        {
            return redirect()->route('mqtt-index')->with('message-fail','Vyskytla se chyba'.$e);
        }
        return redirect()->route('mqtt-index')->with('message','Nastavení smazáno');
    }

    public function update(Request $request, MqttServerSet $idmqtt_server_set)
    {
        $request->except('_token');
        $request->merge(['vlozil' => Auth::user()->id]);
        $idmqtt_server_set->update($request->all());
        return redirect()->route('mqtt-index')->with('message', 'Nastavení upraveno');
    }

    public function create(Request $request)
    {
        $data = $this->validatorRequestu($request);

        if ($data->fails())
        {
            return redirect()->back()->withErrors($data->errors())->with('message-fail', 'Něco se nepovedlo :( ');
        }
        MqttServerSet::create([
            'nazev' => $request->get('nazev'),
            'ipadresa' => $request->get('ipadresa'),
            'vlozil' => Auth::user()->id,
        ]);

        return redirect()->route('mqtt-index')->with('message', 'Nastavení vytvořeno');
    }

    public function updateServer(Request $request)
    {
        MqttServerSet::where('aktivni', '=',1)->update(['aktivni' => 0]);
        $emailSettings = MqttServerSet::find($request->all()['aktivni']);
        $emailSettings->aktivni = 1;
        $emailSettings->update();

        //todo restart service
        return redirect()->route('mqtt-index')->with('message', 'Změněno ');
    }

    protected function validatorRequestu(Request $data)
    {
        return Validator::make($data->all(), [
            'ipadresa' => ['required', 'string'],
            'nazev' => ['required','string'],
        ]);
    }
}
