import dateutil.parser

from ruletypes import RuleType

# elastalert.util includes useful utility functions
# such as converting from timestamp to datetime obj
from util import ts_to_dt

# Modified version of http://elastalert.readthedocs.io/en/latest/recipes/adding_rules.html#tutorial
# to catch events happening outside a certain time range
class OutOfTimeRangeRule(RuleType):
    """ Match if input time is outside the given range """
   
    # Time range specified by including the following properties in the rule:
    required_options = set(['time_start', 'time_end'])

    # add_data will be called each time Elasticsearch is queried.
    # data is a list of documents from Elasticsearch, sorted by timestamp,
    # including all the fields that the config specifies with "include"
    def add_data(self, data):
        for document in data:
            # Convert the timestamp to a time object
            login_time = document['@timestamp'].time()

            # Convert time_start and time_end to time objects
            time_start = dateutil.parser.parse(self.rules['time_start']).time()
            time_end = dateutil.parser.parse(self.rules['time_end']).time()

            # If time is outside office hours
            if login_time < time_start or login_time > time_end:

                # To add a match, use self.add_match
                self.add_match(document)

    # The results of get_match_str will appear in the alert text
    def get_match_str(self, match):
        return "logged in outside %s and %s" % (self.rules['time_start'], self.rules['time_end'])
     
    def garbage_collect(self, timestamp):
      pass