<?php

namespace App\Http\Controllers\Map;

use App\Http\Controllers\Controller;
use App\Models\map\TjBox;
use Illuminate\Http\Request;
use Ramsey\Uuid\Type\Integer;

class TjBoxController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return TjBox::all();
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            "name" => "required",
            "coordinates" => "required",
            "remarks" => "nullable",
        ]);

        $createdTjBox = new TjBox();

        $createdTjBox->name = $request->name;
        $createdTjBox->coordinates = json_encode($request->coordinates);
        $createdTjBox->remarks = $request->remarks;
        $createdTjBox->type = "tjBox";

        $createdTjBox->save();

        return $createdTjBox;
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\TjBox  $tjBox
     * @return \Illuminate\Http\Response
     */
    public function show(TjBox $tjBox)
    {
        return $tjBox->load("upStream", "downStream");
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\TjBox  $tjBox
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, TjBox $tjBox)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\map\TjBox  $tjBox
     * @return \Illuminate\Http\Response
     */
    public function destroy(TjBox $tjBox)
    {
        $loadedTjBox = $this->show($tjBox);

        if ($loadedTjBox->upStream->count() > 0 || $loadedTjBox->downStream->count() > 0)
            return response()->json(["message" => "Cannot delete this TJ Box because it has connected components"], 400);

        $loadedTjBox->delete();

        return response()->json(["message" => "TJ Box deleted successfully"], 200);
    }
}
