#!/usr/bin/env python3

import botocore
import datetime
import time
from aws_cloudwatch_logs_utils.cloudwatch_logs import logger, parse_common_params, logs_tail, \
    LogStreamNotFoundError, TooManyLogStreamsMatched
import argparse

# defaults
live_interval = 3  # seconds
tail_last_items = 100


def main():
    try:
        parser = argparse.ArgumentParser()
        parser.add_argument(
            "-f", "--follow", action='store_true', help="Follow log tail")
        parser.add_argument("-n", type=int, dest='tail',
                            default=10, help="Log tail length")
        parser.add_argument("-s", type=float, dest='tail_last_hours',
                            default=3.0, help="Log tail since <s> hours")

        params = parse_common_params(parser)

        args = parser.parse_args()
        tail = None

        if (args.follow):
            start_time = datetime.datetime.now() - datetime.timedelta(seconds=live_interval)
        else:
            start_time = datetime.datetime.now() - datetime.timedelta(hours=args.tail_last_hours)
            tail = args.tail

        params['start_time'] = start_time
        last_event = None
        seen_events = {}

        last_called = datetime.datetime.now()

        # now do the infinite loop (if --follow)
        while True:
            last_event, seen_events = logs_tail(
                **params,
                last_event=last_event,
                seen_events=seen_events,
                tail=tail,
                no_timestamp=args.no_timestamp
            )

            if not args.follow:
                # no --follow, break loop after single run
                break

            tail = None

            # try to simulate "interval", sleeping for
            diff = datetime.timedelta(
                seconds=live_interval) - (datetime.datetime.now() - last_called)
            if diff.total_seconds() > 0:
                logger.debug(
                    "Sleeping for {}s".format(diff.total_seconds()))
                time.sleep(diff.total_seconds())
            else:
                logger.debug(
                    "Not sleeping, {}s since previous call".format(diff.total_seconds()))

            last_called = datetime.datetime.now()

    except (botocore.exceptions.ClientError, botocore.exceptions.ParamValidationError,
            LogStreamNotFoundError, TooManyLogStreamsMatched) as e:
        print("Error: {}".format(e))
        exit(1)

    except BrokenPipeError:
        exit(0)

    except KeyboardInterrupt:
        exit(2)


if __name__ == '__main__':
    main()
