#!/usr/bin/env python3

import os
import sys
import signal
import getopt
from gempa import CAPS

usage_info = f"""Usage:
  {os.path.basename(__file__)} [options]

Push images into CAPS.

Options:
    -H, --host                   Host to connect to.
    -h, --help                   Display this help message and exit.
    -d, --directory              Input directory to use.
    -n, --network                Network code.
"""


def usage(exitcode=0):
    print(usage_info)
    return exitcode


output = CAPS.Plugin("imageimporter")


def signal_handler(sig, frame):  # pylint: disable=W0613
    print("Caught Ctrl+C!")
    output.quit()
    sys.exit(0)


def sendImage(netcode, stacode, timestamp, filename):
    f = open(filename, "rb")
    if not f:
        return False

    data = f.read()
    f.close()

    output.push(netcode, stacode, "", "CAM", timestamp, 1, 0, "JPG", data)

    return True


def main():
    try:
        opts, _ = getopt.getopt(
            sys.argv[1:], "hH:d:n:", ["help", "host=", "directory=", "network="]
        )
    except getopt.GetoptError as err:
        # print help information and exit:
        print(str(err))  # will print something like "option -a not recognized"
        return usage(2)

    signal.signal(signal.SIGINT, signal_handler)

    addr = None
    directory = None
    netcode = None

    for o, a in opts:
        if o in ["-h", "--help"]:
            return usage()

        if o in ["-H", "--host"]:
            addr = a
        elif o in ["-d", "--directory"]:
            directory = a
        elif o in ["-n", "--network"]:
            netcode = a
        else:
            assert False, "unhandled option"

    if not netcode:
        print("No network code given\n", file=sys.stderr)
        return 1

    if addr:
        try:
            host, port = addr.split(":")
        except BaseException:
            print(f"invalid host address given: {addr}\n", file=sys.stderr)
            return 1
    else:
        host = None
        port = None

    if port:
        try:
            port = int(port)
        except BaseException:
            print(f"invalid port given: {port}\n", file=sys.stderr)
            return 1
    else:
        port = 18002

    if not host:
        host = "localhost"

    output.setHost(host)
    output.setPort(port)
    output.setBufferSize(1 << 30)

    print(f"Looking for images in directory: {directory}\n", file=sys.stderr)
    # Find all images files in the given directory
    for path, _, files in os.walk(directory):
        i = 1
        count = len(files)
        for fn in files:
            if not fn.endswith(".jpg"):
                continue

            toks = fn.split("_")
            if len(toks) < 4:
                continue

            toks = toks[len(toks) - 4 :]

            stacode = toks[1]
            timestamp = CAPS.Time.FromString(toks[2] + toks[3], "%Y%m%d%H%M")

            filename = os.path.join(path, fn)

            timeString = timestamp.iso()
            print(f"Sending image {fn}, {i}/{count}, {timeString}\n", file=sys.stdout)
            sendImage(netcode, stacode, timestamp, filename)
            i = i + 1

    output.quit()
    return 0


if __name__ == "__main__":
    sys.exit(main())
