#!/usr/bin/env python3


# Author: Raghu Rao <raghu.v.rao@gmail.com>

# TODO: this script is similar in functionality to t.  See if t and this
# script can be unified.


import argparse
import datetime
import pytz
import sys

from datetime import datetime
from pytz import utc, timezone, UnknownTimeZoneError


def emit_warning(message):
    print(f"[WARNING] {message}", file=sys.stderr)


def main():
    default_timezone = "Etc/UTC"

    parser = argparse.ArgumentParser(
        description="converts a given time and a timezone into other timezones.",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )
    parser.add_argument(
        "moment",
        type=str,
        help="the time to convert; see the input format option for the default format",
    )
    parser.add_argument(
        "-z",
        "--timezones",
        default="Etc/UTC,US/Pacific,US/Eastern,Asia/Kolkata",
        required=False,
        help="the timezones to which to convert the specified moment",
    )
    parser.add_argument(
        "-t",
        "--in-timezone",
        default=default_timezone,
        required=False,
        help="the timezone in which the moment is",
    )
    parser.add_argument(
        "-i",
        "--input-format",
        default="%Y-%m-%d-%H-%M-%S",
        required=False,
        help="input format (strftime)",
    )
    parser.add_argument(
        "-o",
        "--output-format",
        default="%Y-%m-%d %H:%M:%S %Z(UTC%z)",
        required=False,
        help="output format (strftime)",
    )
    args = parser.parse_args()

    in_format = args.input_format
    out_format = args.output_format

    try:
        input_timezone = timezone(args.in_timezone)
    except UnknownTimeZoneError:
        emit_warning(
            f"Unknown timezone '{args.in_timezone}'; assuming {default_timezone}"
        )
        input_timezone = timezone(default_timezone)

    try:
        moment = datetime.strptime(args.moment, in_format)
    except (KeyError, ValueError):
        emit_warning(f"Cannot understand '{args.moment}'; using current system time")
        moment = datetime.utcnow()
        input_timezone = utc

    moment = input_timezone.localize(moment)
    # Time delta between The UNIX Epoch and now.
    d = moment.astimezone(utc) - datetime(1970, 1, 1, 0, 0, 0, tzinfo=utc)
    print(f"{int(d.total_seconds())} UNIX")  # Ignore microseconds.

    # Work out which timezones we will be using.
    tzs = []
    unknown_tzs = []
    for tz in args.timezones.split(","):
        try:
            tzs.append(timezone(tz.strip()))
        except UnknownTimeZoneError:
            unknown_tzs.append(tz)
    if any(unknown_tzs):
        emit_warning(f"Unknown timezones: {unknown_tzs}")
    if not any(tzs):
        tzs = [timezone("Etc/UTC")]

    for tz in tzs:
        print(f"{moment.astimezone(tz).strftime(out_format)} {tz}")


if __name__ == "__main__":
    main()
