<?php

namespace inter\mysqlStruct;

use Exception;
use inter\mysqlStruct\Column;
use inter\mysqlStruct\Database;
use inter\mysqlStruct\Table;
use inter\storage\mysql\DB;
use PDO;

class Struct
{
    private DB $db;
    private string $database = "";

    // 使用的表
    private array $useTables;

    public function __construct(DB $db)
    {
        $this->db = $db;
    }

    public function AddUseTable(string $tableName): self
    {
        $this->useTables[$tableName] = true;
        return $this;
    }

    public function SelectDatabase(string $database): self
    {
        $this->database = $database;
        return $this;
    }

    public function GetDatabase(): Database
    {
        // 获取表的表字段
        try {
            $stmt = $this->db->query("SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_KEY, c.`TABLE_NAME`, c.`COLUMN_COMMENT`
            FROM INFORMATION_SCHEMA.COLUMNS c
            WHERE TABLE_SCHEMA = '{$this->database}';");
            $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (Exception $e) {
            throw new Exception("查询数据库表结构失败： " + $e->getMessage());
        }
        $database = new Database($this->database);

        $tablesMap = [];
        foreach ($data as $row) {
            if (!empty($this->useTables) && !isset($this->useTables[$row['TABLE_NAME']])) {
                continue;
            }
            if (empty($tablesMap[$row['TABLE_NAME']])) {
                $table = new Table();
                $database->AddTable($table);
                $table->SetName($row['TABLE_NAME']);
                $tablesMap[$row['TABLE_NAME']] = &$table;
            }
            $column = new Column();
            $column->SetName($row['COLUMN_NAME'])
                ->SetComment($row['COLUMN_COMMENT'])
                ->SetType($row['DATA_TYPE'])
                ->SetKeyType($row['COLUMN_KEY']);

            $tablesMap[$row['TABLE_NAME']]->AddColumn($column);
        }

        return $database;
    }
}
