<?php

namespace Wizard\Framework\Database;

use Illuminate\Support\Facades\Schema;

class SchemaDrawer
{
    public $schema;

    public $table;

    public $tables;

    public function __construct()
    {
        $this->tables = $this->getTables();
    }

    public static function createSchema($file_name = null)
    {
        $sd = new self;

        $schema = $sd->list_tables_and_fks();
        if (is_null($file_name)) {
            return $schema;
        } else {
            $f = fopen($file_name, 'w+');
            fwrite($f, $schema);
            fclose($f);
        }

        return true;
    }

    protected static function getTableColumns(string $table_name)
    {
        return Schema::getColumns($table_name);
    }

    protected static function getTableForeignKeys(string $table_name)
    {
        return Schema::getForeignKeys($table_name);
    }

    /**
     * Get the tables in the schema.
     */
    protected function getTables()
    {
        if (is_null($this->tables)) {
            $key = 'DATABASE()';
            $schema = \DB::select('SELECT DATABASE()')[0]->$key;
            $this->tables = Schema::getTables(schema: [$schema]);
        }

        return $this->tables;
    }

    public function list_tables_and_fks(): string
    {
        $fk_labels = false;
        $str = '
digraph mydb { 
	fontname="Helvetica,Arial,sans-serif"
	graph [layout="circo"]
	node [fontname="Helvetica,Arial,sans-serif", shape="record"]
	edge [fontname="Helvetica,Arial,sans-serif"]
';
        foreach ($this->tables as $table) {
            $table_name = $table['name'];
            $str .= "\t".$table_name.'[label="{'.$table_name;
            foreach (self::getTableColumns($table_name) as $column) {
                $col_name = $column['name'];
                $str .= ' | <'.$col_name.'> '.$col_name;
                // TODO: should we show the type?
            }
            $str .= '}"]'."\n";

            $fks = self::getTableForeignKeys($table_name);
            foreach ($fks as $fk) {
                $name = $fk['name'];

                if (! (str_contains($name, 'created_by') || str_contains($name, 'updated_by'))) {
                    $local_column = $fk['columns'];
                    $local_column = (isset($local_column[0])) ? ':'.$local_column[0] : '';
                    $foreign_column = $fk['foreign_columns'];
                    $foreign_column = (isset($foreign_column[0])) ? ':'.$foreign_column[0] : '';
                    $str .= "\t".$table_name.$local_column.' -> '.$fk['foreign_table'].$foreign_column;
                    if ($fk_labels) {
                        $str .= '[label="'.$name."\"];\n";
                    } else {
                        $str .= ";\n";
                    }
                }
            }
            $str .= "\n";
        }
        $str .= '}';

        return $str;
    }
}
