
# -*- coding: utf-8 -*-
from email import charset
from fastapi import APIRouter, Depends,Request
from datetime import timedelta
from sqlalchemy.orm import Session
from database import get_db
from common import security
import json,uuid
from models.base import *
router = APIRouter()

@router.post('/create_api_service')
async def create_api_service(
    request: Request,
    db: Session = Depends(get_db)
):  
    data = await request.body()
    body = data.decode(encoding='utf-8')
    if len(body) > 0:
        print(body)
        body = json.loads(body)
    serviceid = str(uuid.uuid4()).replace("-","")
    serviname = body['servicename']
    datasource = str(uuid.uuid1())
    sqlname = body['sqlname']
    id = str(uuid.uuid4())
    dbtype = body['dbtype']
    if body['dbtype'] == 'pymysql':
        host = body['host']
        user = body['user']
        password = body['password']
        database = body['database']
        port = body['port']
        charset = body['charset']
        create_datasource = DatasourceEntity(id= datasource,name=sqlname,scope=serviceid,dbtype=dbtype,host=host,user=user,password=password,database=database,port=port,charset=charset)
        # db.add()
        # print()
    sqltext = body['sqltext']
    create_command = CommandEntity(id=id,sqltext=sqltext,datasource=datasource,scope=serviceid)
    create_api = ApiServiceEntity(id=serviceid,name=serviname)
    db.add(create_api)
    db.add(create_datasource)
    db.add(create_command)
    db.commit()
    return serviceid

@router.post('/security/login')
def login_for_access_token(
    client_id: str,
    client_secret: str,
    db: Session = Depends(get_db)
):
    app = security.authenticate_app(db, client_id, client_secret)
    print(client_id, client_secret)
    if not app:
        return {
            'code': 1004,
            'msg': '账号错误'
        }

    access_token_expires = timedelta(hours=24)
    access_token = security.create_access_token(
        data={"sub": client_id}, expires_delta=access_token_expires
    )
    return {
        "access_token": access_token, 
        "errmsg": "成功", 
        "errcode": 0
    }