<?php

namespace App\Repositories\Core;

use App\Models\Lote;
use App\Models\Titulo;
use App\Repositories\Contracts\RepositoryInterface;
use App\Repositories\Exceptions\NoEntityDefined;

class BaseEloquentRepository implements RepositoryInterface
{
    protected $entity;

    public function __construct()
    {
        $this->entity = $this->resolveEntity();
    }

    public function getAll()
    {
        return $this->entity->get();
    }

    public function findById($id)
    {
        if (Lote::class) {
            return Lote::find($id);
        } else if (Titulo::class) {
            return Titulo::find($id);
        } else {
            return $this->entity->find($id);
        }

    }

    public function findWhere($column, $valor)
    {
        return $this->entity
            ->where($column, $valor)
            ->get();
    }

    public function findWhereFirst($column, $valor)
    {
        return $this->entity
            ->where($column, $valor)
            ->first();
    }

    public function paginate($totalPage = 10)
    {
        if (Lote::class) {
            return Lote::paginate();
        } else if (Titulo::class) {
            return Titulo::paginate();
        } else {
            return $this->entity->paginate();
        }
    }

    public function store(array $data)
    {
        $this->entity->create($data);
    }

    public function update($id, array $data)
    {
        $entity = $this->findById($id);
        return $entity->update($data);
    }

    public function delete($id)
    {
        return $this->entity->find($id)->delete();
    }

    public function relationShips($relationShips)
    {
        //dd($relationShips);
        $this->entity->hasOne($relationShips);
        return $this->entity;
    }

    public function resolveEntity()
    {
        //dd(!method_exists($this->entity, 'entity'));
        if (method_exists($this->entity, 'entity')) {
            throw new NoEntityDefined;
        }
        return app($this->entity);
    }

}
