import datetime
import pathlib

import aiviro
from aiviro.modules.reader import InvoiceData


class ERPHandler:
    def __init__(self, rdp_robot: "aiviro.RDPRobot", export_folder: pathlib.Path):
        self.r = rdp_robot
        self._export_folder = export_folder

    @aiviro.step
    def handle_story_xx(self, data: InvoiceData, pdf_path: pathlib.Path) -> None:
        """Method called to handle whole process of adding data to ERP"""
        self._start_erp()
        self._open_invoices_with_new_record()
        self._write_to_new_record(data)
        self._attach_pdf(pdf_path)
        self._save_new_record()
        self._close_erp()

    @aiviro.step
    def _start_erp(self) -> None:
        """Method to start ERP program via WIN+R shortcut"""
        self.r.start_process(r"path\to\your\erp\program.exe")

    @aiviro.step
    def _open_invoices_with_new_record(self) -> None:
        """Method to open invoices tab in ERP"""
        self.r.double_click(aiviro.Text("Přijaté faktury", element_index=0))
        self.r.click(aiviro.Text("Nový záznam", element_index=0))

    @aiviro.step
    def _write_to_new_record(self, data: InvoiceData) -> None:
        """Method to write provided data to new record"""
        self.r.type_text(
            element=aiviro.Input("Číslo dokladu", element_index=0),
            text_to_type=data.invoice_id.value,
        )
        self.r.type_text(
            element=aiviro.Input("Celková částka", element_index=0),
            text_to_type=str(data.total_amount.value),
        )
        self.r.type_text(
            element=aiviro.Input("Celková částka bez DPH", element_index=0),
            text_to_type=str(data.total_amount_without_tax.value),
        )
        self.r.type_text(
            element=aiviro.Input("Daňový doklad", element_index=0),
            text_to_type=datetime.date.strftime(data.tax_date.value, "%d.%m.%Y"),
        )

    @aiviro.step
    def _attach_pdf(self, pdf_path: pathlib.Path) -> None:
        """Method to attach pdf to the new record"""
        self.r.transfer_files_to_guests_clipboard(pdf_path)
        self.r.click(aiviro.Button("Připojit ze schránky", element_index=0))

    @aiviro.step
    def _save_new_record(self) -> None:
        """Method to save new record simply by clicking on the Save button.
        And transfer generated files from guest clipboard to the export folder on the host machine.
        """
        self.r.click(aiviro.Button("Uložit", element_index=0))
        self.r.click(aiviro.Text("Nový záznam", element_index=0))
        self.r.transfer_files_from_guests_clipboard(self._export_folder, copy=True)

    @aiviro.step
    def _close_erp(self) -> None:
        """Method to close ERP program"""
        self.r.click(aiviro.Button("Zavřít", element_index=0))
        self.r.click(aiviro.Button("Ano", element_index=0))
