"""Sends TXT message with GMail.

This is a demonstration on how to send an text message with Python.
In this example, we use GMail to send the SMS message,
but any host can work with the correct SMTP settings.
Each carrier has a unique SMS gateway hostname.
This method is completely free and can be useful in a variety of ways.

Video: https://youtu.be/hKxtMaa2hwQ
Turn on: https://myaccount.google.com/lesssecureapps
"""

import asyncio
import re
from email.message import EmailMessage
from typing import Collection, List, Tuple, Union

import aiosmtplib

HOST = "smtp.gmail.com"
# https://kb.sandisk.com/app/answers/detail/a_id/17056/~/list-of-mobile-carrier-gateway-addresses
# https://www.gmass.co/blog/send-text-from-gmail/
CARRIER_MAP = {
    "verizon": "vtext.com",
    "tmobile": "tmomail.net",
    "sprint": "messaging.sprintpcs.com",
    "at&t": "txt.att.net",
    "boost": "smsmyboostmobile.com",
    "cricket": "sms.cricketwireless.net",
    "uscellular": "email.uscc.net",
}


# pylint: disable=too-many-arguments
async def send_txt(
    num: Union[str, int], carrier: str, email: str, pword: str, msg: str, subj: str
) -> Tuple[dict, str]:
    to_email = CARRIER_MAP[carrier]

    # build message
    message = EmailMessage()
    message["From"] = email
    message["To"] = f"{num}@{to_email}"
    message["Subject"] = subj
    message.set_content(msg)

    # send
    send_kws = dict(
        username=email, password=pword, hostname=HOST, port=587, start_tls=True
    )
    res = await aiosmtplib.send(message, **send_kws)  # type: ignore
    msg = "failed" if not re.search(r"\sOK\s", res[1]) else "succeeded"
    return res


async def send_txts(
    nums: Collection[Union[str, int]],
    carrier: str,
    email: str,
    pword: str,
    msg: str,
    subj: str,
) -> List[Tuple[dict, str]]:
    tasks = [send_txt(n, carrier, email, pword, msg, subj) for n in set(nums)]
    return await asyncio.gather(*tasks)


# if __name__ == "__main__":
def send_text_message(
    message,
    subject="",
    phone_number="6513669018",
    carrier="tmobile",
    email="zirkespython@gmail.com",
    email_password="ktzx uysc dtzi xvky",
):
    coro = send_txt(phone_number, carrier, email, email_password, message, subject)
    asyncio.run(coro)
