# -*- coding: utf-8 -*-
"""
@File: dev.py
@Date: 2020-09-14
@author: A2TEC
@section MODIFYINFO 수정정보
- 수정자/수정일   : 수정내역
- 2022-01-14/hsj100@a2tec.co.kr : refactoring
@brief: Developments Test
"""
import struct

from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
import bcrypt
from starlette.requests import Request

from main_rest.app.common import consts
from main_rest.app import models as M
from main_rest.app.database.conn import db, Base
from main_rest.app.database.schema import Users, UserLog

from main_rest.app.utils.extra import FernetCrypto, AESCryptoCBC, AESCipher
from custom_logger.main_log import main_logger as LOG


# mail test
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart


def send_mail():
    """
    구글 계정사용시 : 보안 수준이 낮은 앱에서의 접근 활성화

    :return:
    """
    sender = 'jolimola@gmail.com'
    sender_pw = '!ghkdtmdwns1'
    # recipient = 'hsj100@a2tec.co.kr'
    recipient = 'jwkim@daooldns.co.kr'
    list_cc = ['cc1@gmail.com', 'cc2@naver.com']
    str_cc = ','.join(list_cc)

    title = 'Test mail'
    contents = '''
    This is test mail
    using smtplib.
    '''

    smtp_server = smtplib.SMTP(  # 1
        host='smtp.gmail.com',
        port=587
    )

    smtp_server.ehlo()  # 2
    smtp_server.starttls()  # 2
    smtp_server.ehlo()  # 2
    smtp_server.login(sender, sender_pw)  # 3

    msg = MIMEMultipart()  # 4
    msg['From'] = sender  # 5
    msg['To'] = recipient  # 5
    # msg['Cc'] = str_cc  # 5
    msg['Subject'] = contents  # 5
    msg.attach(MIMEText(contents, 'plain'))  # 6

    smtp_server.send_message(msg)  # 7
    smtp_server.quit()  # 8


router = APIRouter(prefix='/dev')


@router.get('/test', summary='테스트', response_model=M.SWInfo)
async def test(request: Request):
    """
    ## ELB 상태 체크용 API

    **결과**
     - SWInfo
    """

    a = M.SWInfo()

    a.name = '!ekdnfeldpsdptm1'
    # a.name = 'testtesttest123'
    simpleEnDecrypt = FernetCrypto()
    a.data1 = simpleEnDecrypt.encrypt(a.name)
    a.data2 = bcrypt.hashpw(a.name.encode('utf-8'), bcrypt.gensalt())

    t = bytes(a.name.encode('utf-8'))

    enc = AESCryptoCBC().encrypt(t)
    dec = AESCryptoCBC().decrypt(enc)

    t = enc.decode('utf-8')

    # enc = AESCipher('daooldns12345678').encrypt(a.name).decode('utf-8')
    # enc = 'E563ZFt+yJL8YY5yYlYyk602MSscPP2SCCD8UtXXpMI='
    # dec = AESCipher('daooldns12345678').decrypt(enc).decode('utf-8')

    a.data3 = f'enc: {enc}, {t}'
    a.data4 = f'dec: {dec}'
    
    a.name = '!ekdnfeldpsdptm1'
    
    
    # simpleEnDecrypt = SimpleEnDecrypt()
    a.data5 = simpleEnDecrypt.encrypt(a.name)
    a.data6 = bcrypt.hashpw(a.name.encode('utf-8'), bcrypt.gensalt())

    key = consts.ADMIN_INIT_ACCOUNT_INFO['aes_cbc_key']

    t = bytes(a.name.encode('utf-8'))

    enc = AESCryptoCBC(key).encrypt(t)
    dec = AESCryptoCBC(key).decrypt(enc)

    t = enc.decode('utf-8')

    # enc = AESCipher('daooldns12345678').encrypt(a.name).decode('utf-8')
    # enc = 'E563ZFt+yJL8YY5yYlYyk602MSscPP2SCCD8UtXXpMI='
    # dec = AESCipher('daooldns12345678').decrypt(enc).decode('utf-8')

    print(f'key: {key}')
    a.data7 = f'enc: {enc}, {t}'
    a.data8 = f'dec: {dec}'

    
    eee = "gAAAAABioV5NucuS9nQugZJnz-KjVG_FGnaowB9KAfhOoWjjiQ4jGLuYJh4Qe94mT_lCm6m3HhuOJqUeOgjppwREDpIQYzrUXA=="
    a.data8  = simpleEnDecrypt.decrypt(eee)
    
    return a


# @router.post("/vectorImageSearch/vit/imageGenerate/imagen/report", summary="벡터 이미지 검색(clip-vit) - imagen, report 생성", response_model=M.ResponseBase)
# async def vactor_vit_report(request: Request, request_body_info: M.VectorImageSearchVitReportReq):
    # """
    # ## 벡터 이미지 검색(clip-vit) - imagen, report 생성
    # > imagen AI를 이용하여 이미지 생성 후 vector 검색 그후 종합결과 이미지 생성
    
    # ### Requriements
    # > - googlecli 설치(https://cloud.google.com/sdk/docs/install?hl=ko#linux)
    
    # ### options
    # > - modelType -> b32,b16,l14,l14_336
    # > - indexType -> l2,cos
    
    # """
    # response = M.ResponseBase()
    # try:       
    #     if request_body_info.modelType not in [M.VitModelType.b32, M.VitModelType.b16, M.VitModelType.l14, M.VitModelType.l14_336]:
    #         raise Exception(f"modelType is invalid (current value = {request_body_info.modelType})")
        
    #     if request_body_info.indexType not in [M.VitIndexType.cos, M.VitIndexType.l2]:
    #         raise Exception(f"indexType is invalid (current value = {request_body_info.indexType})")
        
    #     # query_image_path = imagen_generate_temp_image_path(image_prompt=request_body_info.prompt) #imagen
    #     query_image_path = gemini_image(request_body_info.prompt) #gemini
    #     report_image_path = f"{os.path.splitext(query_image_path)[0]}_report.png"
        
    #     vactor_request_data = {'query_image_path' : query_image_path,
    #                            'index_type' : request_body_info.indexType, 
    #                            'model_type' : request_body_info.modelType,
    #                            'report_path' : report_image_path}

    #     vactor_response = requests.post('http://localhost:51002/api/services/faiss/vector/search/vit/report', data=json.dumps(vactor_request_data))
        
    #     if vactor_response.status_code != 200:
    #         raise Exception(f"response error: {json.loads(vactor_response.text)['error']}")
        
    #     if json.loads(vactor_response.text)["error"] != None:
    #         raise Exception(f"vector error: {json.loads(vactor_response.text)['error']}")
        
    #     if rest_config.config != 'release':
    #         # remote 폴더에 이미지 저장
    #         sftp_client.remote_copy_data(local_path=report_image_path, 
    #                                     remote_path=os.path.join(rest_config.remote_folder, f"imagen_report_vit_{request_body_info.prompt}_{D.date_file_name()}.png"))
    #     else:
    #         shutil.copy(report_image_path, os.path.join(rest_config.local_folder, f"imagen_report_vit_{request_body_info.prompt}_{D.date_file_name()}.png"))
         
    #     # Clean up temporary files
    #     if 'query_image_path' in locals():
    #         if os.path.exists(query_image_path):
    #             os.remove(query_image_path)
    #             del query_image_path
    #     if 'report_image_path' in locals():
    #         if os.path.exists(report_image_path):
    #             os.remove(report_image_path)
    #             del report_image_path
        
    #     return response.set_message()
    
    # except Exception as e:
    #     LOG.error(traceback.format_exc())
        
    #     # Clean up temporary files
    #     if 'query_image_path' in locals():
    #         if os.path.exists(query_image_path):
    #             os.remove(query_image_path)
    #             del query_image_path
    #     if 'report_image_path' in locals():
    #         if os.path.exists(report_image_path):
    #             os.remove(report_image_path)
    #             del report_image_path
                
    #     return response.set_error(error=e)