
import pytesseract
from datetime import datetime
import os
from pathlib import Path

class ImageProcessor:

    def __init__(self, installation_path):
        self.installation_path = installation_path
        print("Image processor object created")
        self.debug = False
        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 - Image Processor - Debug Logging enabled = " + str(
                    enable) + "\n")
            else:
                f = open(self.debug_path, "w")
                f.write(current_time + " : " + "Email Service - Text Converter - Image Processor - Debug Logging enabled = " + str(
                    enable) + "\n")
        else:
            f = open(self.debug_path, "a")
            f.write(
                current_time + " : " + "Email Service - Text Converter - Image Processor - Debug Logging enabled = " + str(enable) + "\n")
        f.close()


    def process(self, image):
        current_time = datetime.now().strftime("%Y/%d/%m_%H:%M:%S")
        pytesseract.pytesseract.tesseract_cmd = self.installation_path
        # ocr_result = pre_process(image)
        ocr_result = pytesseract.image_to_string(image)
        if ocr_result:
            if self.debug:
                f = open(self.debug_path, "a")
                f.write(
                    current_time + " : " + "Email Service - Text Converter - Image Processor - Returning valid ocr result" + "\n")
                f.close()
            return ocr_result
        else:
            if self.debug:
                f = open(self.debug_path, "a")
                f.write(current_time + " : " + "ERROR: Email Service - Text Converter - Image Processor - Invalid returned ocr result" +  "\n")
                f.close()