# ====================================================================
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ====================================================================

# Uses an LDIF file from a LDAP search / export to track account ages

from settings import UID_CREATED_LDIF
import datetime
import sys,os

LDAP_MASS_IMPORTED_BEFORE = datetime.date(2009,5,19)

class UIDDates(object):
    def __init__(self):
        self.dates = {}

    def get_earliest_year(self):
        return LDAP_MASS_IMPORTED_BEFORE.year

    def get_latest_year(self):
        self.ensure_data()
        year = self.get_earliest_year()
        for d in list(self.dates.values()):
            if d.year > year:
               year = d.year
        return year

    def get_year(self, uid):
        self.ensure_data()
        d = self.dates.get(uid, None)
        if d:
            return d.year
        return None

    def decorate(self, people):
        self.ensure_data()
        if_none_year = self.get_latest_year()
        for p in people:
            uid = p["uid"]
            if uid in self.dates:
                p["year"] = self.dates[uid].year
            else:
                # Assume it's a newer account than our LDIF
                p["year"] = if_none_year

    def ensure_data(self):
        # Changes infrequently and manually, just load when first needed
        if not self.dates:
            self._refresh()
    def _refresh(self):
        if not os.path.exists(UID_CREATED_LDIF):
            sys.stderr.write("Missing UID/Created LDIF file: %s\n" % UID_CREATED_LDIF)
        try:
            person = {}
            self.dates = {}
            ldif = open(UID_CREATED_LDIF, "r")
            for line in ldif.readlines():
                if line.startswith("# "):
                    if "uid" in person and "created" in person:
                        self.dates[person["uid"]] = person["created"]
                    person = {}
                elif ":" in line:
                    k, v = [x.strip() for x in line.split(":")][0:2]
                    if k == "createTimestamp":
                         k = "created"
                         ymd = [int(x) for x in (v[0:4],v[4:6],v[6:8])]
                         v = datetime.date(*ymd)
                    person[k] = v
        except IOError as e:
             sys.stderr.write("Unable to process created LDIF file: %s\n" % e)
