from typing import List

import json
from app.core.crud import CRUDBase
from app.models.admin import Api, Menu, Codegen
from app.schemas.codegen import CodegenCreate, CodegenUpdate
from app.utils.db import DatabaseInfo
from app.utils.codegen import CodeGenerator

class CodegenController(CRUDBase[Codegen, CodegenCreate, CodegenUpdate]):
    def __init__(self):
        super().__init__(model=Codegen)

    async def is_exist(self, name: str) -> bool:
        return await self.model.filter(name=name).exists()

    async def import_table(self, connect: str='', importTables: List[str] = None) -> Codegen:

        default_frontend_config = {
            "editable": True,
            "listable": True,
            "sortable": True,
            "filterable": False,
            "filter_operator": '=',  # = | >= 默认过滤操作符为包含
            "display_type": 'text',  # 默认显示类型为文本
        }
        
        cnt = 0
        
        with DatabaseInfo(
            host="lt.330770.xyz",
            port=3307,
            user="root",
            password="rap_sky",
            database="rpa"
        ) as db:
            
            for table_name in importTables:
                table = db.get_table_structure(table_name)
                # result.append(fields)
                fields = table.get('fields')
                for field in fields:
                    # if field.name in ['id']:
                    if 'editable' not in field:
                        field['editable'] = field['required']
                    new_data = {**default_frontend_config, **field}
                    field.update(**new_data)
                description = table.get('tableComment')
                await self.create(CodegenCreate(name=table_name, description=description , fields=json.dumps(fields,ensure_ascii=False)))
                cnt += 1

        return cnt
    
    async def preview(self, table_id):
        generator = CodeGenerator()
        config_orm = await self.get(id=table_id)
        entity_config = await config_orm.to_dict()
        generated_files = generator.generate_files(entity_config, 'relation-demo', {})
        return generated_files
    
    
codegen_controller = CodegenController()
