

import pdfplumber
import cv2
from ImageProcessor import ImageProcessor
from datetime import datetime
import os
from pathlib import Path
from pdf2image import convert_from_path


class TextConverter:

    def __init__(self):
        print("Text Converter object created")
        self.debug = False
        self.image_processor = ImageProcessor(r'C:\Program Files\Tesseract-OCR\tesseract.exe')
        self.debug_path = Path.cwd() / "Log/AutoMailClassifier/LogAutoMailClassifier.txt"


    def enable_disable_log_debugging(self, enable):
        self.debug = enable
        current_time = datetime.now().strftime("%Y/%d/%m_%H:%M:%S")
        if not os.path.isfile(self.debug_path):
            target_folder = Path.cwd() / "Log/AutoMailClassifier"
            if not os.path.exists(target_folder):
                os.makedirs(target_folder)
                f = open(self.debug_path, "x")
                f.write(current_time + " : " + "Email Service - Text Converter - Debug Logging enabled = " + str(enable) + "\n")
            else:
                f = open(self.debug_path, "w")
                f.write(current_time + " : " + "Email Service - Text Converter - Debug Logging enabled = " + str(enable) + "\n")
        else:
            f = open(self.debug_path, "a")
            f.write(current_time + " : " + "Email Service - Text Converter - Debug Logging enabled = " + str(enable) + "\n")
        f.close()
        self.image_processor.enable_disable_log_debugging(enable)


    def set_install_folder(self, path):
        current_time = datetime.now().strftime("%Y/%d/%m_%H:%M:%S")
        if self.debug:
            f = open(self.debug_path, "a")
            f.write(current_time + " : " + "Email Service - Text Converter - Setting install folder for image processor: " + str(path) + "\n")
            f.close()
        self.image_processor = ImageProcessor(path)


    def file_to_text(self, filepath):
        current_time = datetime.now().strftime("%Y/%d/%m_%H:%M:%S")
        if filepath.lower().endswith(('.pdf')):
            if self.debug:
                f = open(self.debug_path, "a")
                f.write(current_time + " : " + "Email Service - Text Converter - Processing pdf file: " + str(filepath) + "\n")
                f.close()
            return self.pdf_to_text(filepath)
        elif filepath.lower().endswith(('.png')) or filepath.lower().endswith(('.jpg')):
            if self.debug:
                f = open(self.debug_path, "a")
                f.write(current_time + " : " + "Email Service - Text Converter - Processing png or jpg file: " + str(filepath) + "\n")
                f.close()
            return self.image_to_text(filepath)
        elif filepath.lower().endswith(('.txt')):
            if self.debug:
                f = open(self.debug_path, "a")
                f.write(current_time + " : " + "Email Service - Text Converter - Processing txt file: " + str(filepath) + "\n")
                f.close()
            return self.text_to_text(filepath)
        else:
            if self.debug:
                f = open(self.debug_path, "a")
                f.write(current_time + " : " + "ERROR - Email Service - Text Converter - File format not compatible - " + str(filepath) + "\n")
                f.close()


    def pdf_to_img(self,filepath):
        mother_path = os.path.dirname(filepath)
        pages = convert_from_path(filepath, 500)
        counter = 0
        actual_files = []
        for page in pages:
            page.save(mother_path + "\out" + str(counter) + ".jpg", 'JPEG')
            actual_files.append(mother_path + "\out" + str(counter) + ".jpg")
            counter += 1
        return actual_files


    def pdf_to_text(self, filepath):
        text = ""
        with pdfplumber.open(filepath) as pdf:
            for i in range(0, len(pdf.pages)):
                page = pdf.pages[i]
                text_process = page.extract_text()
                text += text_process
        if text == "":
            files = self.pdf_to_img(filepath)
            for item in files:
                text += self.image_to_text(item)
        else:
            return text


    def text_to_text(self, filepath):
        current_time = datetime.now().strftime("%Y/%d/%m_%H:%M:%S")
        text = ""
        if filepath.endswith(('EMAIL_BODY.txt')):
            return text
        else:
            if self.debug:
                f = open(self.debug_path, "a")
                f.write(current_time + " : " + "Email Service - Text Converter - Processing a valid txt file: " + str(
                    filepath) + "\n")
                f.close()
            with open(filepath, 'r') as file:
                text = file.read()
            return text


    def image_to_text(self, filepath):
        img = cv2.imread(filepath)
        text = self.image_processor.process(img)
        return text