import glob
import os
import shutil
import time

import pandas
import datetime

from services.email.service import send_email
from logging import getLogger, basicConfig, INFO

# from company_budget_records import insert_budget_record

logger = getLogger(__name__)
basicConfig(filename=__name__, level=INFO)


def parse_xl_files_and_copy_to_database():
    completed = "bank_excels/completed"
    incoming = "bank_excels/incoming"
    pandas.set_option("display.max_columns", None)
    pandas.set_option("display.width", 1200)

    current_directory = os.getcwd()
    # current_directory = "/home/berkay/git-evyos/wag-management-api"
    absolute_path = os.path.join(current_directory, incoming)

    excel_files = glob.glob(os.path.join(absolute_path, "*.xls*"))
    for file_path in excel_files:
        xl_file = pandas.read_excel(file_path)
        xl_frame = pandas.DataFrame(xl_file)
        iban = ""
        for row in xl_frame.itertuples():
            if "IBAN" in str(row[3]).upper():
                iban = str(row[5]).replace(" ", "")
            if not str(row[1]) == "nan" and not str(row[2]) == "nan":
                if len(str(row[1]).split("/")) > 2:
                    insert_dict = dict(
                        iban=str(iban),
                        bank_date=datetime.datetime.strptime(
                            str(row[1]), "%d/%m/%Y-%H:%M:%S"
                        ).__str__(),
                        channel_branch=str(row[3]),
                        currency_value=(
                            float(str(row[4]).replace(",", "")) if row[4] else 0
                        ),
                        balance=float(str(row[5]).replace(",", "")) if row[5] else 0,
                        additional_balance=(
                            float(str(row[6]).replace(",", "")) if row[6] else 0
                        ),
                        process_name=str(row[7]),
                        process_type=str(row[8]),
                        process_comment=str(row[9]),
                        bank_reference_code=str(row[15]),
                    )
                    logger.info(f"Insert Dict: {insert_dict}")
                    print(f"Insert Dict: {insert_dict}")
                    # find_or_create, found = EdmBudgetRecords.find_or_create(**insert_dict)
                    # find_or_create, found = insert_budget_record(insert_dict)
                    find_or_create, found = None, None
                    if found:
                        send_html = f"""
                        <br/>
                        <h1>Bank Excel File</h1>
                        <p>Bank Excel File is processed</p>
                        <br/>
                        <h3>{str(find_or_create.bank_date)}</h3>
                        <h3>{str(find_or_create.process_comment)}</h3>
                        <h3>{str(find_or_create.currency_value)}</h3>
                        <p>Thank you</p>
                        <p>Wag Management</p>
                        <p>Sincere Regards</p>
                        """
                        try:
                            send_email(
                                subject="Bank Excel File",
                                receivers=["mehmet.karatay@hotmail.com"],
                                html=send_html,
                            )
                        except Exception as e:
                            print(f"Error: {e}")
                        finally:
                            print("Email is sent")
        shutil.move(
            file_path,
            os.path.join(current_directory, completed, os.path.basename(file_path)),
        )


if __name__ == "__main__":
    while True:
        parse_xl_files_and_copy_to_database()
        time.sleep(int(os.getenv("PARSER_SEQUENCE", 60)))
