<?php

namespace App\Services\Database;

use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class TouchDB
{
    public string $databaseName;
    public array $extraDateColumns;
    private Collection $collection;

    public function __construct()
    {
        $this->collection = new Collection();
        $this->databaseName = Schema::getConnection()->getDatabaseName();
        $this->extraDateColumns = [];
    }

    /**
     * @return Collection
     */
    public function getTableList(): Collection
    {
        return $this->getAll()->pluck('table_name')->unique()->values();
    }

    /**
     * @return Collection
     */
    public function getAll(): Collection
    {
        $query = DB::select("SELECT TABLE_NAME AS table_name, COLUMN_NAME AS column_name, DATA_TYPE AS type FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ?", [$this->databaseName]);
        foreach ($query as $item) {
            $this->collection->push($item);
        }

        return $this->collection;
    }

    /**
     * @param $model
     * @return Collection
     */
    public function getAllByModel($model): Collection
    {
        $class = resolve($model);
        $table = $class->getTable();
        return $this->getAll()->where('table_name', '=', $table)->values();
    }

    /**
     * @param $model
     * @return Collection
     */
    public function getAllDateColumnsByModel($model): Collection
    {
        $class = resolve($model);
        $table = $class->getTable();
        return $this->getAllDateColumns()->where('table_name', '=', $table)->values();
    }

    /**
     * @return Collection
     */
    public function getAllDateColumns(): Collection
    {
        if (!empty($this->extraDateColumns)) {
            $extraDateColumns = $this->getExtraDateColumns();
            $extra = function ($itemType) use ($extraDateColumns) {
                foreach ($extraDateColumns as $extraDateColumn) {
                    if ($itemType->column_name == $extraDateColumn) {
                        $itemType->type = 'date';
                    }
                }
            };

            return $this->getAll()->filter(function ($item) use ($extra) {
                $extra($item);
                return $item->type == 'date' || $item->type == 'datetime' || $item->type == 'timestamp';
            })->unique('column_name')->values();
        }

        return $this->getAll()->filter(function ($item) {
            return $item->type == 'date' || $item->type == 'datetime' || $item->type == 'timestamp';
        })->unique('column_name')->values();
    }

    public function getExtraDateColumns(): array
    {
        return $this->extraDateColumns;
    }

    public function setExtraDateColumns($array)
    {
        $this->extraDateColumns = $array;
    }
}
