from PIL import Image,ImageSequence
import os
from PDFNetPython3.PDFNetPython import PDFDoc, Optimizer, SDFDoc, PDFNet
from pypdf import PdfReader, PdfWriter
import ffmpeg
from pdf2image import convert_from_path
import os
import shutil
import time



base_path_storage = '/home/appuser/maskrestdj/maskapi/DocumentCompressionSystem/output/'


#Image
def compress_image(input_path, output_path, quality=85):
    print("input_path", input_path)
    print("output_path", output_path), 
    image = Image.open(input_path)
    
    print('Imge size', image)
    # output_path = base_path_storage + output_path
    # output_path = output_path

    ####################
    sizeim = os.path.getsize(input_path)
    # resolim = image.size[0]*image.size[1]

    if input_path.lower().endswith('.png'):
        format_='PNG'
    elif input_path.lower().endswith('.jpeg'):
        format_='JPEG'
    elif input_path.lower().endswith('.jpg'):
        format_='JPEG'
    elif input_path.lower().endswith('.bmp'):
        format_='JPEG' 
        print('BMP Selected')   
    elif input_path.lower().endswith('.webp'):
        format_='JPEG'    

    print("We are here")
    print(sizeim,quality)
    if sizeim<70000:
        if quality > 100:
            image.save(output_path, format=format_, quality=quality, optimize=True)
        else:
            image.save(output_path, format=format_, quality=100, optimize=True)
    if sizeim<100000:
        if quality > 80:
            image.save(output_path, format=format_, quality=quality, optimize=True)
        else:
            image.save(output_path, format=format_, quality=80, optimize=True)
    elif 100000<sizeim<290000:
        if quality > 50:
            image.save(output_path, format=format_, quality=quality, optimize=True)
        else:
            print(output_path, format_)
            image.save(output_path, format=format_, quality=50, optimize=True)
    elif 290000<sizeim<600000:
        if quality > 29:
            image.save(output_path, format=format_, quality=quality, optimize=True)
        else:
            print(output_path, format_)
            image.save(output_path, format=format_, quality=29, optimize=True)
    elif 600000<sizeim<1000000:
        if quality > 10:
            image.save(output_path, format=format_, quality=quality, optimize=True)
        else:
            image.save(output_path, format=format_, quality=10, optimize=True)
    else:
        image.save(output_path, format=format_, quality=10, optimize=True)
    # print('Reached Here')
    # image.save(output_path, format=format_, quality=10, optimize=True)
    print('[INFO] Reached Here')
    ####################

    # image.save(output_path, format='JPEG', quality=quality, optimize=True)

#Image PDFs
def pdf_to_images(pdf_path, output_folder):
    images = convert_from_path(pdf_path)
    # Save each page as an image
    for i, image in enumerate(images):
        image_file_path = os.path.join(output_folder, f'{i + 1}_page_.png')
        image.save(image_file_path, 'PNG')

def images_to_pdf(image_folder, output_pdf_path):

    # Get all image files from the specified folder
    image_files = [os.path.join(image_folder, img) for img in os.listdir(image_folder) if img.endswith(('png', 'jpg', 'jpeg'))]
    image_files.sort()  # Sort files if needed (e.g., by name)

    # Open the first image and convert the rest to PDF
    if image_files:
        first_image = Image.open(image_files[0])
        image_list = [Image.open(img) for img in image_files[1:]]

        # Save as a multi-page PDF
        first_image.save(output_pdf_path, save_all=True, append_images=image_list)
        print(f'Saved PDF: {output_pdf_path}')
    else:
        print("No images found in the specified folder.")



#Computer Generated PDF
def compress_computer_generated_pdf(input_path,output_path):
    reader = PdfReader(input_path)
    writer = PdfWriter()

    for page in reader.pages:
        writer.add_page(page)

    if reader.metadata is not None:
        writer.add_metadata(reader.metadata)

    for page in writer.pages:
        page.compress_content_streams()  # This is CPU intensive!

    with open(output_path, "wb") as f:
        writer.write(f)

#Video Compression 
def compress_video(input_file, output_file, crf=23):
    print('fgxhgjh')
    ffmpeg.input(input_file).output(output_file, vcodec='libx264', crf=crf).run()


def pp(filename,filedata,quality_in,base_path_storage):
    data = ''
    try:
        if filename.lower().endswith('.pdf'):
            extn='.pdf'
        elif filename.lower().endswith('.png'):
            extn='.png'
        elif filename.lower().endswith('.jpg'):
            extn='.jpg'
        elif filename.lower().endswith('.jpeg'):
            extn='.jpg'
        elif filename.lower().endswith('.mp4'):
            extn='.mp4'
        elif filename.lower().endswith('.avi'):
            extn='.avi'
        elif filename.lower().endswith('.mov'):
            extn='.mov'
        elif filename.lower().endswith('.bmp'):
            extn='.bmp'
        elif filename.lower().endswith('.webp'):
            extn='.webp'
        else:
            return -1

        output_pathg = base_path_storage+str(time.time())+extn
        with open(output_pathg, "wb") as f:
            f.write(filedata)
        print("OKAY : ")
        output_pathg_size = os.path.getsize(output_pathg)
        if output_pathg_size <100:
            
        a,b,c = process(filename,output_pathg,quality_in,base_path_storage)
        print("WE GIT A ", a)
        with open(a, "rb") as f:
            data = f.read()
        if b!=0:
            shutil.rmtree(b)
            shutil.rmtree(c)
        else:
            os.remove(a)
    except:
        return ''
    return data
    
def process(ename,path,quality_in,base_path_storage):
    print('Recieved ::',ename)
    print(ename.lower())
    if '.pdf' in ename.lower():
        folder_name = base_path_storage+str(time.time())
        os.mkdir(folder_name)
        os.mkdir(folder_name+'_o')
        pdf_to_images(path, folder_name)
        os.listdir(folder_name)

        for img in os.listdir(folder_name):
            print("folder_name", folder_name)
            print("img", img)
            compress_image(folder_name+'/'+img, folder_name+'_o'+'/'+img, quality=quality_in)

        images_to_pdf(folder_name+'_o', folder_name+'/out.pdf')

        compress_computer_generated_pdf(path,folder_name+'/out_o.pdf')

        if os.path.getsize(folder_name+'/out.pdf') > os.path.getsize(folder_name+'/out_o.pdf'):
            return folder_name+'/out_o.pdf',folder_name,folder_name+'_o'
        else:
            return folder_name+'/out.pdf'  ,folder_name,folder_name+'_o'
            
    elif '.png' in ename.lower():
        op_path = str(time.time())+'_.png'
        compress_image(path, op_path, quality=quality_in)
        return op_path,0,0
    
    elif '.bmp' in ename.lower():
        op_path = str(time.time())+'_.bmp'
        compress_image(path, op_path, quality=quality_in)
        print('Output_path ::',op_path)
        return op_path,0,0
    elif '.webp' in ename.lower():
        op_path = str(time.time())+'_.webp'
        compress_image(path, op_path, quality=quality_in)
        return op_path,0,0
    
    elif '.jpg' in ename.lower() or '.jpeg' in ename.lower():
        op_path = str(time.time())+'_.jpg'
        compress_image(path, op_path, quality=quality_in)
        return op_path,0,0
    
    elif '.mp4' in ename.lower():
        op_path = base_path_storage +str(time.time())+'_.mp4'
        print('dtfyguh')
        compress_video(path, op_path, crf=40) #### Tune the ratio
        print('VideCOmp')
        return op_path,0,0
    elif '.avi' in ename.lower():
        op_path = base_path_storage + str(time.time())+'_.avi'
        print('dtfyguh')
        compress_video(path, op_path, crf=40) #### Tune the ratio
        print('VideCOmp')
        return op_path,0,0
    elif '.mov' in ename.lower():
        op_path = base_path_storage + str(time.time())+'_.mov'
        print('dtfyguh')
        compress_video(path, op_path, crf=40) #### Tune the ratio
        print('VideCOmp')
        return op_path,0,0
    else:
        print('FIlename ::',ename)
        return -1,-1,-1


# if __name__ == "__main__":
#     ename = "1.bmp"
#     path = "/home/appuser/UAT/DocumentCompressionSystem/Compression Demop/1.bmp"
#     quality_in = 20
#     base_path_storage = "/home/appuser/UAT/DocumentCompressionSystem/output/"
#     a,b,c= process(ename,path,quality_in,base_path_storage)
#     print(a)



this is the compression code and main code pp is getting run and i want to add 2 logic here if the size of the file is less then 100 kb den dont do comprsssion and passs as it is ,.. the second logic is after comnpression the size of the compressed file increase then the orignal file then just pass the orignal file else pass the compressed image