<?php namespace Lucent\Edge;

use Illuminate\Support\Facades\DB;
use Lucent\LucentException;
use PDOException;
use stdClass;

class EdgeRepo
{

    public function __construct()
    {
    }

    public function insert(Edge $edge): void
    {
        try {
            DB::table("edges")->insert($edge->toDB());
        } catch (PDOException $e) {
            if ($e->getCode() == 23505) {
                throw new LucentException("Edge already exists");
            }
            throw $e;
        }

    }

    public function update(string $from, EdgeCollection $edges): void
    {
        $edgesDB = collect($edges)->map(fn($e) => $e->toDB())->toArray();
        DB::table("edges")->where("source", $from)->delete();
        DB::table("edges")->insert($edgesDB);
    }


    public function findAll(): EdgeCollection
    {
        $edges = DB::table("edges")->get();
        return new EdgeCollection(...$edges->map([$this, 'mapEdge'])->toArray());
    }

    public function mapEdge(stdClass $edge): Edge
    {

        return new Edge(
            source: $edge->source,
            target: $edge->target,
            sourceSchema: $edge->sourceSchema,
            targetSchema: $edge->targetSchema,
            field: $edge->field,
            rank: $edge->rank,
            depth: $edge->depth ?? 0
        );

    }

    public function remove(Edge $edge): void
    {
        DB::table("edges")
            ->where("source", $edge->source)
            ->where("target", $edge->target)
            ->where("sourceSchema", $edge->sourceSchema)
            ->where("targetSchema", $edge->targetSchema)
            ->where("field", $edge->field)
            ->delete();
    }

}
