from phpserialize import loads, dumps
from fpdf import FPDF
import math
import os
import sys
import json
import pydicom
import numpy as np
from PIL import Image
from PyPDF2 import PdfMerger
#fonction pour des-serializer

# US : 6 images par page
# MR / CT / PET : 4 images par page
# DX / CR (ou tout le reste) : 1 par page
##############################################################CONVERSION#########################################################################
def adjust_contrast(image):
    # Apply contrast adjustment here
    # For example, you can normalize the pixel values
    normalized_image = (image - np.min(image)) / (np.max(image) - np.min(image)) * 255
    return normalized_image.astype(np.uint8)

def dcmToJpeg(input_file, output_folder,basefilename):
    # verifier si dossier de sortie existe, si n existe pas , creer
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    # charger le dicom
    dicom_data = pydicom.dcmread(input_file)

    frames_list = []

    # verifier si le dicom possede multiples frames
    #si oui
    if 'NumberOfFrames' in dicom_data:
        #si oui parcourir chaun
        for i in range(dicom_data.NumberOfFrames):
            #Generer le nom du frame
            output_file = os.path.join(output_folder, basefilename + f"_{i}.jpeg")

            #obtenir l image du frame
            frame = dicom_data.pixel_array[i]

            #setter le contraste au frame
            adjusted_frame = adjust_contrast(frame)

            #convertir pour une image PIL
            image = Image.fromarray(adjusted_frame)

            #sauvegarder comme PDF
            image.save(output_file)

            #qjouter l'image a la liste
            frames_list.append(output_file)
    #si un seul frame
    else:
        #generer le nom
        output_file = os.path.join(output_folder, basefilename + ".jpeg")

        #obtenir l'image
        frame = dicom_data.pixel_array

        #setter le contraste
        adjusted_frame = adjust_contrast(frame)

        #convertir pour une image PIL
        image = Image.fromarray(adjusted_frame)

        #Sauvegarder comme PDF
        image.save(output_file)

        #Ajouter chemin a la liste
        frames_list.append(output_file)

    return frames_list

#Fonction pour ajouter le chemin des fichiers dans une liste de fichiers
def ajouterCheminListe(liste,chemin):
    nvListe=[]
    for file in liste:
        nvListe.append(chemin+file)
    return nvListe


def des_seliarizer(liste):

    #Convertir la liste
    phpArray = loads(liste.encode())

    # Extaire les valeurs et convertir les bytecodes en strings
    pythonList = [value.decode() for value in phpArray.values()]
    
    #retourner
    return pythonList


###################################################################### Créer les PDF #################################################################################
#fonction pour créer le pdf et retourner le chemin
def creerPDF(modalite,listeImages,destinationFile):
    if modalite=="US":
        creerPDF_US(listeImages,destinationFile)
    elif modalite == "MR" or modalite == "CT" or modalite == "PET":
        creerPDF_MR_CT_PET(listeImages,destinationFile)
    else:
        creerPDF_DX_CR(listeImages,destinationFile,"")


def creerPDF_US(filesPath, fileDestination, remarques=""):
    # Variables
    phtoSize = 65.55
    photoX = 35
    xSpacing = 80
    photoY = 60
    ySpacing = 40

    quantiteImages = len(filesPath) # nombre de frames
    indexDesImages = 0 # index pages
    maxDeImagesParPage = 6 # limite d'iages par page
    nbPages = math.ceil(quantiteImages / maxDeImagesParPage) # calcul numero de pages
    # Création du PDF
    pdf = FPDF()
    pdf.add_page()

    # Ajout des remarques
    pdf.set_font("Helvetica", size=12)
    pdf.set_text_color(0, 0, 0)
    pdf.set_xy(10, 50)
    pdf.multi_cell(0, 10, remarques)

    # Pour chaque page


    # ajouter les images et si necessaire créer une nouvelle
    for j in range(nbPages) : #numero de pages
        #ajouter logo
        pdf.image("public/img/Logo-Atima.png", 10, 5, w=0, h=30, type="PNG")
        pdf.image("public/img/Logo-Atima.png", 170, 5, w=0, h=30, type="PNG")

        #premiere image
        if indexDesImages < quantiteImages:
            pdf.image(filesPath[indexDesImages], photoX, photoY, w=0, h=phtoSize)
            indexDesImages += 1
            
        #2nd image
        if indexDesImages < quantiteImages:
            pdf.image(filesPath[indexDesImages], photoX + xSpacing, photoY, w=0, h=phtoSize)
            indexDesImages += 1

        #3eme image
        if indexDesImages < quantiteImages:
            pdf.image(filesPath[indexDesImages], photoX, photoY + ySpacing*2, w=0, h=phtoSize)
            indexDesImages += 1

        #4eme image
        if indexDesImages < quantiteImages:
            pdf.image(filesPath[indexDesImages], photoX + xSpacing, photoY + ySpacing*2, w=0, h=phtoSize)
            indexDesImages += 1

        #5eme image
        if indexDesImages < quantiteImages:
            pdf.image(filesPath[indexDesImages], photoX, photoY + ySpacing*4, w=0, h=phtoSize)
            indexDesImages += 1
        
        #6eme image
        if indexDesImages < quantiteImages:
            pdf.image(filesPath[indexDesImages], photoX + xSpacing, photoY + ySpacing*4, w=0, h=phtoSize)
            indexDesImages += 1
        
        #if imagePageCount % 2 == 0:
        #    photoX += xSpacing
        #if imagePageCount % 2 == 0 and imagePageCount % 4 == 0:
        #    photoX = 13.33
        #    photoY += ySpacing

        # Ajout d'une nouvelle page si nécessaire
        if j < nbPages - 1:
            pdf.add_page()

    # Sauvegarde du PDF
    pdf.output(fileDestination)


def creerPDF_MR_CT_PET(filesPath, fileDestination, remarques=""):
    # Variables
    phtoSize = 80
    photoX = 20
    xSpacing = 90
    photoY = 60
    ySpacing = 50

    quantiteImages = len(filesPath) # nombre de frames
    indexDesImages = 0 # index pages
    maxDeImagesParPage = 4 # limite d'iages par page
    nbPages = math.ceil(quantiteImages / maxDeImagesParPage) # calcul numero de pages
    # Création du PDF
    pdf = FPDF()
    pdf.add_page()

    # Ajout des remarques
    pdf.set_font("Helvetica", size=12)
    pdf.set_text_color(0, 0, 0)
    pdf.set_xy(10, 50)
    pdf.multi_cell(0, 10, remarques)

    # Pour chaque page


    # ajouter les images et si necessaire créer une nouvelle
    for j in range(nbPages) : #numero de pages
        #ajouter logo
        pdf.image("public/img/Logo-Atima.png", 10, 5, w=0, h=30, type="PNG")
        pdf.image("public/img/Logo-Atima.png", 170, 5, w=0, h=30, type="PNG")

        #premiere image
        if indexDesImages < quantiteImages:
            pdf.image(filesPath[indexDesImages], photoX, photoY, w=0, h=phtoSize)
            indexDesImages += 1
            
        #2nd image
        if indexDesImages < quantiteImages:
            pdf.image(filesPath[indexDesImages], photoX + xSpacing, photoY, w=0, h=phtoSize)
            indexDesImages += 1

        #3eme image
        if indexDesImages < quantiteImages:
            pdf.image(filesPath[indexDesImages], photoX, photoY + ySpacing*2, w=0, h=phtoSize)
            indexDesImages += 1

        #4eme image
        if indexDesImages < quantiteImages:
            pdf.image(filesPath[indexDesImages], photoX + xSpacing, photoY + ySpacing*2, w=0, h=phtoSize)
            indexDesImages += 1

        # Ajout d'une nouvelle page si nécessaire
        if j < nbPages - 1:
            pdf.add_page()

    # Sauvegarde du PDF
    pdf.output(fileDestination)


from PIL import Image

def creerPDF_DX_CR(filesPath, fileDestination, remarques=""):
    # Création du PDF
    pdf = FPDF()
    pdf.add_page()

    # Ajouter le logo
    #pdf.image("public/img/Logo-Atima.png", 10, 10, w=0, h=20, type="PNG")
    #pdf.image("public/img/Logo-Atima.png", 170, 10, w=0, h=20, type="PNG")

    # Ajouter des remarques
    pdf.set_font("Helvetica", size=12)
    pdf.set_text_color(0, 0, 0)
    pdf.set_xy(10, 35)
    pdf.multi_cell(0, 10, remarques)

    # Pour chaque fichier
    for i, file_path in enumerate(filesPath):
        # Obtenir la taille de l'image
        img = Image.open(file_path)
        img_width, img_height = img.size


        #ajouter logo : 

        pdf.image("public/img/Logo-Atima.png", 10, 10, w=30, h=30, type="PNG")
        pdf.image("public/img/Logo-Atima.png", 167, 10, w=30, h=30, type="PNG")


        # Calculer le ratio pour ajuster la taille de l'image
        page_width, page_height = pdf.w, pdf.h - 130#ceci est la taille apparament     # Réduire la hauteur de la marge supérieure et inférieure
        width_ratio = page_width / img_width
        height_ratio = page_height / img_height

        if width_ratio < height_ratio:
            img_width *= width_ratio
            img_height *= width_ratio
        else:
            img_width *= height_ratio
            img_height *= height_ratio

        x = (page_width - img_width) / 2
        y = (page_height - img_height) / 2 + 65  # Ajouter une marge supérieure pour le logo et le texte

        # Ajouter l'image à la position calculée
        pdf.image(file_path, x, y, w=img_width, h=img_height)

        # Ajout d'une nouvelle page si ce n'est pas le dernier fichier
        if i < len(filesPath) - 1:
            pdf.add_page()

    # Sauvegarde du PDF
    pdf.output(fileDestination)



#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ÃSSEMBLER DES PDF~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~é
def merge_pdfs(pdf_list, output_path):
    # creer PdfMerger
    merger = PdfMerger()

    # mettre les psd dans le pdfMerger
    for pdf in pdf_list:
        merger.append(pdf)

    #ouvrir pdf et sauvegarder
    with open(output_path, 'wb') as output_file:
        merger.write(output_file)
    #fermer
    merger.close()

    # retour du fichier
    return output_path