import os

from config_isbank import Config

from redbox import EmailBox
from redbox.query import FROM, UNSEEN, OR


host = "10.10.2.34"
port = 993
username = "isbank@mehmetkaratay.com.tr"
password = "system"
authorized_iban = "4245-0093333"
authorized_iban_cleaned = authorized_iban.replace("-", "")

box = EmailBox(host=host, port=port, username=username, password=password)

filter_mail = OR(FROM(Config.MAILBOX), FROM(Config.KARATAY))
filter_print = f"{Config.MAILBOX} & {Config.KARATAY}"
# banks_mails = mailbox.search(from_=filter_mail, unseen=True) bununla denemeyin
# banks_mails = mailbox.search(FROM(filter_mail) & UNSEEN)


def reader_service():
    mailbox = box.inbox
    banks_mails = mailbox.search(filter_mail & UNSEEN)
    print(
        f"Service is reading mailbox [{username}] with mail sender [{filter_print}] with count : {len(banks_mails)}"
    )
    for banks_mail in banks_mails:
        message_attc = (
            lambda fn: f"FROM: {banks_mail.from_}, SEEN: {banks_mail.seen} MSG: email_message.is_multipart Downloaded attachment: {fn}"
        )
        message_non_attc = (
            lambda fn: f"FROM: {banks_mail.from_}, SEEN: {banks_mail.seen} MSG: Handle non-multipart email Downloaded attachment: {fn}"
        )
        # mail_subject = banks_mail.subject
        email_message = banks_mail.email
        full_path = lambda fn: str(Config.UNREAD_PATH) + str(fn)
        completed_path = lambda fn: str(Config.COMPLETED_PATH) + "/" + str(fn)
        file_exists = lambda fn: not os.path.exists(
            full_path(fn)
        ) and not os.path.exists(completed_path(fn))
        if email_message.is_multipart():  # Check if email has multipart content
            for part in email_message.walk():
                content_disposition = part.get(
                    "Content-Disposition"
                )  # Each part can be an attachment
                if content_disposition and "attachment" in content_disposition:
                    if filename := part.get_filename():
                        if authorized_iban_cleaned in str(filename) and file_exists(
                            filename
                        ):
                            with open(full_path(filename), "wb") as f:
                                print(message_attc(filename))
                                f.write(
                                    part.get_payload(decode=True)
                                )  # Save attachment
        else:  # Handle non-multipart email, though this is rare for emails with attachments
            content_disposition = email_message.get("Content-Disposition")
            if content_disposition and "attachment" in content_disposition:
                if filename := email_message.get_filename():
                    if authorized_iban_cleaned in str(filename) and file_exists(
                        filename
                    ):
                        with open(full_path(filename), "wb") as f:
                            print(message_non_attc(filename))
                            f.write(email_message.get_payload(decode=True))
