import tempfile
import logging
from pathlib import Path

from PyPDF2 import PdfReader
from pdf2docx import Converter

from .base import Base
from ..utils.document_converter import *
from ..utils.errors import WrongConverterError
from ..utils.font_detection import FontDetector
from ..utils.document_converter import (
    run_shell_command,
    extract_text_data,
    create_txt_file,
    extract_figure_from_img,
    convert_pdf_to_docx,
)

class PdfConverter(Base):
    def __init__(self) -> None:
        super().__init__()

    def _check_if_scanned_pdf(self):
        print(self.input_file_path)
        pdf_reader = PdfReader(self.input_file_path)
        if pdf_reader.pages[0].extract_text() != "":
            return False
        else:
            return True

    def _convert(self):
        format = self.output_file_format
        if format == ".txt":
            text_data = extract_text_data(self.input_file_path)
            return create_txt_file(text_data, self.input_file_path, self.input_file_name)
        elif format in [".docx", ".doc"]:
            return convert_pdf_to_docx(
                self.input_file_path, self.input_file_name, format
            )
        elif format in self._supported_formats:
            format = format.replace(".", "")
            shell_command = f'soffice --infilter="writer_pdf_import" --headless --convert-to {format} "{self.input_file_path}" --outdir "{Path(self.input_file_path).parent}"'
            print(f"Shell Command: {shell_command}") 
            return run_shell_command(shell_command)

    def _run_ocr(self):
        font_detector = FontDetector()
        with tempfile.TemporaryDirectory(dir=".") as tmp_dir:
            img_locations = extract_images_from_pdf(self.input_file_path, tmp_dir)
            img_locations, figure_location = extract_figure_from_img(img_locations)
            hocr_file_locations = create_hocr_file(img_locations, font_detector)
            background_img_locations = create_background_images(img_locations)
            pdf_file_locations = combine_text_image(
                hocr_file_locations, background_img_locations, figure_location
            )
            file_location = merge_pdf_files(pdf_file_locations, self.input_file_path)
        self.input_file_path = file_location
        file_location, status = self._convert()
        print(f"OCR File Location: {file_location}")
        return file_location, status

    def convert(self, input_file_path: str, output_file_format: str):
        super().initialize_details(input_file_path, output_file_format)
        if self.input_file_format != ".pdf":
            raise WrongConverterError("PdfConverter", self.input_file_format)
        if self.input_file_format == self.output_file_format:
            return "Output file format is the same as input file format", False
        if self._check_if_scanned_pdf():
            return self._run_ocr()
        else:
            return self._convert()

if __name__ == "__main__":
    p = PdfConverter("Final Report.docx", ".pdf")
    print(p.convert())
