# -*- coding: utf-8 -*-
"""
Created on Mon Apr 17 11:40:14 2023

@author: DEV profield01
"""

import os

import fitz
import os
from PIL import Image
from PIL.TiffImagePlugin import Image as Img
import io
# Converting pdf to image

def convert_pdf2img(input_image, out_path, out_format, resize, resolution):
    """Converts pdf to image and generates a file by page"""
    # Open the document
    input_pdf = fitz.open(io.BytesIO(input_image))
    output_files = []
    # Iterate through the pages
    for page in input_pdf:
        rotate = int(0)
        zoom_x = 2
        zoom_y = 2
        # The zoom factor is equal to 2 in order to make text clear
        # Pre-rotate is to rotate if needed.
        mat = fitz.Matrix(zoom_x, zoom_y).prerotate(rotate)
        pix = page.get_pixmap(matrix=mat, alpha=False)
        # Get the current resolution and calculate the new resolution based on the input parameter
        current_resolution = pix.resolution
        new_resolution = fitz.Resolution(resolution)
        
        # Scale the pixmap to the new resolution and size
        scale_x = new_resolution[0] / current_resolution[0]
        scale_y = new_resolution[1] / current_resolution[1]
        pix.scale(scale_x, scale_y)
        img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)

        # Resize image
        resized_image = img.resize((resize[0], resize[1]))
        output_file = f"{os.path.splitext(os.path.basename(input_image))[0]}_{page.number+1}.{out_format}"
        output_path = os.path.join(out_path, output_file)
        resized_image.save(output_path, dpi=new_resolution, quality=100)

        output_files.append(output_file)
    input_pdf.close()
    return output_files

# Converting eps file to image

def convert_eps2img(input_image, out_path, out_format, resize, resolution, scale=4):
    # open the EPS file
    eps_image = Image.open(io.BytesIO(input_image))
    eps_image = eps_image.convert('RGB')
    eps_image.load(scale=scale)

    # resizing image
    resized_image = eps_image.resize(resize, Image.LANCZOS)
    # Set resolution
    resized_image.info['dpi'] = (resolution, resolution)
    
    out_file_name = os.path.splitext(os.path.basename(input_image))[0]

    # determine the file extension from the output format argument
    if out_format.lower() == 'jpg':
        extension = 'jpg'
        resized_image.info['jfif_density'] = (resolution,resolution)
        # save the image with the determined extension
        #out_file_path = os.path.join(out_path, out_file_name + '.' + extension)
        # get the DPI information from the resized image's metadata
        info = resized_image.info
        dpi = [round(x) for x in info.get("dpi", (0, 0))]
        resized_image.save(out_file_path, quality=100, dpi=dpi)
    elif out_format.lower() == 'png':
        extension = 'png'
    elif out_format.lower() == 'webp':
        extension = 'webp'
    else:
        raise ValueError('Invalid output format')

    # save the image with the determined extension
    out_file_path = os.path.join(out_path, out_file_name + '.' + extension)
    resized_image.save(out_file_path, quality=100)

# Converting image file to image

def convert_image2img(input_image, out_path, out_file_name, out_format, resize, resolution):
    image = Image.open(input_image)
    image = image.convert('RGB')
    # Resize image
    resized_image = image.resize(resize, Image.LANCZOS)
    # Set resolution
    resized_image.info['dpi'] = (resolution, resolution)

    # determine the file extension from the output format argument
    if out_format.lower() == 'jpg':
        extension = 'jpg'
        resized_image.info['jfif_density'] = (resolution,resolution)
        # save the image with the determined extension
        out_file_path = os.path.join(out_path, out_file_name + '.' + extension)
        # get the DPI information from the resized image's metadata
        info = resized_image.info
        dpi = [round(x) for x in info.get("dpi", (0, 0))]
        resized_image.save(out_file_path, quality=100, dpi=dpi)
       
    elif out_format.lower() == 'png':
        extension = 'png'
    elif (out_format.lower() == 'jpg' or  out_format.lower() == 'jpeg'):
        extension = 'jpg'
    elif out_format.lower() == 'webp':
        extension = 'webp'
    else:
        raise ValueError('Invalid output format')

    # save the image with the determined extension
    out_file_path = os.path.join(out_path, out_file_name + '.' + extension)
    resized_image.save(out_file_path, quality=100)
    
# Converting tiff file to image

def convert_tiff2img(input_image, out_path, out_format, resize, resolution):
    # open the image
    image = Img.open(io.BytesIO(input_image))
    # resizing image
    resized_image = image.resize(resize, Image.LANCZOS)
    # Set resolution
    resized_image.info['dpi'] = (resolution, resolution)

    out_file_name = os.path.splitext(os.path.basename(input_image))[0]

    # determine the file extension from the output format argument
    if out_format.lower() == 'jpg':
        extension = 'jpg'
        resized_image.info['jfif_density'] = (resolution,resolution)
        # save the image with the determined extension
        out_file_path = os.path.join(out_path, out_file_name + '.' + extension)
        # get the DPI information from the resized image's metadata
        info = resized_image.info
        dpi = [round(x) for x in info.get("dpi", (0, 0))]
        resized_image.save(out_file_path, quality=100, dpi=dpi)
        return
    elif out_format.lower() == 'png':
        extension = 'png'
    elif out_format.lower() == 'webp':
        extension = 'webp'
    else:
        raise ValueError('Invalid output format')

    # save the image with the determined extension
    out_file_path = os.path.join(out_path, out_file_name + '.' + extension)
    resized_image.save(out_file_path, quality=100)
    
# checking the input file type
def convert_file2img(input_file, extension, out_path, out_file_name, out_format='jpg', resize=(256,256), resolution=96):
    """Converts input file to image and saves in out_path"""
    if extension == 'pdf':
        return convert_pdf2img(input_file, out_path, out_file_name, out_format=out_format, resize=resize, resolution=resolution)
    elif extension == 'eps':
        return convert_eps2img(input_file, out_path, out_file_name, out_format=out_format, resize=resize, scale=4, resolution=resolution)
    elif extension == 'tiff':
        return convert_tiff2img(input_file, out_path, out_file_name, out_format=out_format, resize=resize, resolution=resolution)
    elif extension in ('jpg', 'jpeg', 'png', 'bmp', 'gif'):
        return convert_image2img(input_file, out_path, out_file_name, out_format=out_format, resize=resize, resolution=resolution)
    else:
        raise ValueError('Invalid input file type')

