<?php

namespace inter\gen;

use inter\mysqlStruct\Database;
use inter\phpStruct\Attr;
use inter\phpStruct\Field2Attr;
use inter\phpStruct\File;
use inter\phpStruct\Func;
use inter\phpStruct\PHPClass;
use inter\phpStruct\Table2PHPClass;
use inter\utils\Mkdir;
use inter\utils\Names;

class DbStruct2ClassProcess
{
    private Database $database;
    /** @var File[] */
    private array $files;
    /** @var ProcessConfig */
    public ProcessConfig $config;
    public string $filePath = "";


    public function __construct(ProcessConfig $config, Database $database)
    {
        $this->database = $database;
        $this->config = $config;
    }

    /**
     * @return File[]
     */
    public function  GetFiles(): array
    {
        if (empty($this->files)) {
            $this->database2file();
        }
        return $this->files;
    }

    /**
     * 数据库转文件
     */
    private function  database2file()
    {
        $mkdir = new Mkdir($this->config->savePath . "/" . $this->config->GetNamespace());
        $mkdir->mkdirByNamespace();
        $this->filePath = $mkdir->Namespace2Path();

        foreach ($this->database->GetTables() as  $table) {
            $class = new Table2PHPClass();
            $class->SetTable($table)->SetClassName($this->tableName2fileName($table->GetName()))
                ->SetExtends($this->config->extends);

            $file = new File();
            $file->SetPath($this->filePath);
            $file->SetFileName($class->GetClassName())
                ->SetNamespace($this->config->GetNamespace())
                ->AddClass($class)->SetUses($this->config->getUses());

            foreach ($table->GetColumns() as $column) {
                $attr = new Field2Attr();
                $attr->SetColumn($column)->SetName($this->fieldName2AttrName($column->GetName()));
                $class->AddAttr($attr);
                if ($this->config->isHasGetFunc) {
                    $func = new Func();
                    $func->SetName("get" . Names::Camelize($column->GetName()));
                    $class->AddFunc($func);
                }
                if ($this->config->isHasSetFunc) {
                    $func = new Func();
                    $func->SetName("get" . Names::Camelize($column->GetName()));
                    $class->AddFunc($func);
                }
            }

            $this->files[] = $file;
        }
    }


    /**
     * 表名称转文件名称
     */
    private function tableName2fileName(string $tableName): string
    {
        return $this->config->fileNamePrefix . ucfirst(Names::Camelize($tableName)) . $this->config->fileNameSuffix;
    }

    /**
     * 表字段转类属性
     */
    private function fieldName2AttrName(string $fieldName): string
    {
        return ucfirst(Names::Camelize($fieldName));
    }
}
