import json
import os
import boto3
import tempfile
from ultralytics import YOLO
import os
from dotenv import load_dotenv
from models import ImageProcessingResult
from mongoengine import DoesNotExist
from datetime import datetime

load_dotenv()
# DigitalOcean Space credentials
SPACE_NAME = os.environ.get('SPACE_NAME')
AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')

def download_image(file_key):
    s3 = boto3.client('s3',
                      region_name='nyc3',
                      endpoint_url='https://nyc3.digitaloceanspaces.com',
                      aws_access_key_id=AWS_ACCESS_KEY_ID,
                      aws_secret_access_key=AWS_SECRET_ACCESS_KEY)

    temp_dir = tempfile.mkdtemp()  # Create a temporary directory
    temp_file_path = os.path.join(temp_dir, os.path.basename(file_key))
    with open(temp_file_path, 'wb') as f:
        s3.download_fileobj(SPACE_NAME, file_key, f)
    return temp_file_path

def process_image(file_path):
    model = YOLO(os.getcwd()+"/train12/weights/best.pt")
    result = model.predict(source=file_path, show=False, save=False, show_labels=False, show_conf=False, conf=0.4, save_txt=False, save_crop=False, line_width=2)
    os.remove(file_path)
    prediction_result = result[0]
    if(isinstance(prediction_result.tojson(),str)):
        extracted_result = json.loads(prediction_result.tojson())
        if len(extracted_result) > 0:
            extracted_gun_type = extracted_result[0]['name']
            return extracted_gun_type
        else:
            return None
    else:
        return None
    
def save_processing_result(file_path, fiParkingSlots, cars_count,partnersid,locationame,raw_file):
    try:
        document = ImageProcessingResult.objects.get(fsLocationName=locationame)
        # Update the fields of the existing document
        document.file_path = raw_file
        document.fiParkingSlots = str(fiParkingSlots)
        document.cars_count = str(cars_count)
        document.fsPartnerId = str(partnersid)
        document.fsLocationLat=""
        document.fsLocationLong=""
        document.fdUpdateAt=datetime.now() 
        # Save the updated document
        document.save()
    except DoesNotExist:
        # Create a new document if none was found with the given fsLocationName
        document = ImageProcessingResult(
            file_path=raw_file,
            fiParkingSlots=str(fiParkingSlots),
            cars_count=str(cars_count),
            fsPartnerId=str(partnersid),
            fsLocationName=str(locationame),
            fsLocationLat="",
            fsLocationLong="",
            fdCreateAt=datetime.now() 
        )
        # Save the new document
        document.save()
    
def process_Parkimage(file_path,partnersid,locationame,raw_file):
    model = YOLO(os.getcwd()+"/park/best.pt")
    try:
        result = model.predict(source=file_path, show=False, save=False, show_labels=False, show_conf=False, conf=0.7, save_txt=False, save_crop=False, line_width=2)
    except Exception as e:
        print(f"Error during model prediction: {e}")
        return None
    # os.remove(file_path)
    prediction_result = result[0]
    if(isinstance(prediction_result.tojson(),str)):
        try:
            extracted_result = json.loads(prediction_result.tojson())
        except json.JSONDecodeError as e:
            print(f"Error decoding JSON: {e}")
            return None
        
        fiParkingSlots = 0
        cars_count = 0
        for obj in extracted_result:
            if 'name' in obj:
                if obj['name'] == 'vacant':
                    fiParkingSlots += 1
                elif obj['name'] == 'car':
                    cars_count += 1
        
        save_processing_result(file_path, fiParkingSlots, cars_count,partnersid,locationame,raw_file)
        return fiParkingSlots, cars_count
    else:
        return None
    

