# This Python file uses the following encoding: utf-8
import os
import io
import sys
import csv
import shutil
from PyPDF2 import PdfReader, PdfWriter
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from PySide6.QtWidgets import QApplication, QWidget, QFileDialog
from PySide6.QtCore import QFile, QIODevice

# Important:
# You need to run the following command to generate the ui_form.py file
#     pyside6-uic form.ui -o ui_form.py, or
#     pyside2-uic form.ui -o ui_form.py
from ui_form import Ui_Widget

import rc_files


class Widget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_Widget()
        self.ui.setupUi(self)
        self.ui.file_selector.clicked.connect(self.file_selector)
        self.ui.file_template.clicked.connect(self.file_template)
        self.ui.create_button.clicked.connect(self.create_button)
        self.selected_file = False
        self.selected_template = False
        self.filepath_template = ""
        self.filepath = ""
        self.img_dir = os.path.join(os.path.dirname(__file__), "images")
        self.font_dir = os.path.join(os.path.dirname(__file__), "FONTS")

    def qrc_to_bytes(self, filename):
        file = QFile(filename)
        if not file.open(QIODevice.ReadOnly):
            raise RuntimeError(file.errorString())
            return
        f = io.BytesIO(file.readAll().data())
        return f

    def enable_create(self):
        if self.selected_file and self.selected_template:
            self.ui.create_button.setEnabled(True)

    def file_selector(self):
        self.filepath = QFileDialog.getOpenFileName(self, "Επιλογή Αρχείου")
        if self.filepath[0]:
            ext = os.path.splitext(self.filepath[0])[-1].lower()
            if ext != ".csv":
                self.ui.label_3.setText("Το αρχείο πρέπει να είναι της μορφής .csv")
                self.selected_file = False
            else:
                self.ui.label_3.setText("{}".format(self.filepath[0]))
                self.selected_file = True
                self.in_file = self.filepath[0]
                self.file_path = os.path.dirname(self.filepath[0])
        self.enable_create()

    def file_template(self):
        self.filepath_template = QFileDialog.getOpenFileName(self, "Επιλογή Αρχείου")
        if self.filepath_template[0]:
            ext = os.path.splitext(self.filepath_template[0])[-1].lower()
            if ext != ".pdf":
                self.ui.label_4.setText("Το αρχείο πρέπει να είναι της μορφής .pdf")
                self.selected_template = False
            else:
                self.ui.label_4.setText("{}".format(self.filepath_template[0]))
                self.selected_template = True
                self.in_template = self.filepath_template[0]
                self.template_path = os.path.dirname(self.filepath_template[0])
        self.enable_create()

    def create_button(self):
        with open(self.in_file) as fin:
            csvin = csv.DictReader(fin)
            self.create_certificates(csvin)

    def create_certificates(self, csv_dict):
        count = 0
        shutil.copyfile(
            "{}".format(self.filepath_template[0]),
            "{}/RESULT.pdf".format(self.file_path),
        )
        for in_row in csv_dict:
            count += 1
            packet = io.BytesIO()
            pdfmetrics.registerFont(
                TTFont("NotoMedium", self.qrc_to_bytes(":/FONTS/NotoSans-Medium.ttf"))
            )
            pdfmetrics.registerFont(
                TTFont(
                    "NotoSemiMedium",
                    self.qrc_to_bytes(":/FONTS/NotoSans-SemiCondensedMedium.ttf"),
                )
            )
            # pdfmetrics.registerFont(TTFont('NotoRegular', '{}/NotoSans-Regular.ttf'.format(self.font_dir)))
            # pdfmetrics.registerFont(TTFont('NotoBold', '{}/NotoSans-Bold.ttf'.format(self.font_dir)))
            # pdfmetrics.registerFont(TTFont('NotoSemi', '{}/NotoSans-SemiCondensed.ttf'.format(self.font_dir)))
            # pdfmetrics.registerFont(TTFont('NotoSemiMedium', '{}/NotoSans-SemiCondensedMedium.ttf'.format(self.font_dir)))

            can = canvas.Canvas(packet, pagesize=A4)
            can.setFont("NotoMedium", 22)
            x = can._pagesize[0] / 2
            can.drawString(x, 315, "{} {}".format(in_row["SURNAME"], in_row["NAME"]))
            can.setFont("NotoSemiMedium", 18)
            can.drawString(x, 250, "{}".format(in_row["DEPARTMENT"]))
            can.save()

            packet.seek(0)
            new_pdf = PdfReader(packet)

            existing_pdf = PdfReader(open("{}/RESULT.pdf".format(self.file_path), "rb"))
            output = PdfWriter()

            for page in existing_pdf.pages:
                output.add_page(page)
            page = existing_pdf.pages[0]
            page.merge_page(new_pdf.pages[0])
            output.add_page(page)

            outputStream = open("{}/RESULT.pdf".format(self.file_path), "wb")
            output.write(outputStream)
            outputStream.close()
            self.ui.label_4.setText(
                "Το αρχείο PDF δημιουργήθηκε εντός του φακέλου του .csv"
            )
            self.ui.create_button.setEnabled(False)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    widget = Widget()
    widget.show()
    sys.exit(app.exec())
