from fastapi import APIRouter,BackgroundTasks,HTTPException
import sqlite3
from passlib.context import CryptContext
import subprocess
from pydantic import BaseModel
ModelIndoorTrainer=APIRouter(prefix="/Trainer")
TrainingProcess2={}

def TrainModel(UserId):
    global TrainingProcess2
    if TrainingProcess2.get(UserId,False) and TrainingProcess2.get(UserId).poll():
        raise HTTPException(status_code=400,detail="Model is already training.")
    TrainingProcess2[UserId]=subprocess.Popen(["python","./IndoorLocalization/IndoorlocalizationTrainer.py",f"{UserId}"])
    TrainingProcess2[UserId]=None


class DataType(BaseModel):
    Email:str
    Password:str
@ModelIndoorTrainer.post("/TrainIndoorModel")
async def SpeachToTextEndPoint(Tasks:BackgroundTasks,Data:DataType):
    global TrainingProcess2
    try:    
        
        connect=sqlite3.connect("DataBase/DataBase.bd")
        cursor=connect.execute(f'''
                        SELECT UserId,Password FROM Users where Email='{Data.Email}' 
                        ''')
        if len(cursor.fetchall())==1:
            HasedPassword=cursor.fetchall()[0][1]
            UserId=cursor.fetchall()[0][0]
        State=Data.Password==HasedPassword
        if State:
            if TrainingProcess2.get(UserId,False) and TrainingProcess2.get(UserId).poll() is None:
                raise HTTPException(status_code=400,detail="Model is already training.")
            Tasks.add_task(TrainModel,args=[UserId])
            return{"message":"Training Started"}
            

        else:
            return {"Status":False,"Message":"Email or Password is not correct"}
    except Exception as e:
        return {"Status":False,"Message":f"{e}"}
    
    

    
@ModelIndoorTrainer.post("/TrainIndoorModelStatus")
async def SpeachToTextEndPoint(Data:DataType):
    global TrainingProcess2
    try:    
        
        
        connect=sqlite3.connect("DataBase/DataBase.bd")
        cursor=connect.execute(f'''
                        SELECT UserId, Password FROM Users where Email='{Data.Email}' 
                        ''')
        if len(cursor.fetchall())==1:
            HasedPassword=cursor.fetchall()[0][1]
            UserId=cursor.fetchall()[0][0]
        State=Data.Password==HasedPassword
        if State:
            if TrainingProcess2.get(UserId,False) and TrainingProcess2.get(UserId).poll() is None:
                return{"message":"Model still Training "}
            else:
                return{"message":"Model Training ended"}
            

        else:
            return {"Status":False,"Message":"Email or Password is not correct"}
    except Exception as e:
        return {"Status":False,"Message":f"{e}"}