import couchdb
import os, datetime
from uuid import uuid4
couch = couchdb.Server("http://127.0.0.1:5984/")
db = couch["busjourneys"]

def withindate(sd, ed):
    today = datetime.date.today()
    s = datetime.datetime.strptime(sd, "%Y%m%d").date()
    if ed == "00000000":
        return s <= today
    else:
        e = datetime.datetime.strptime(ed, "%Y%m%d").date()
        return s <= today and today <= e

date = "20100726"
dir = os.path.join("GMPTE_CIF_"+date)
for f in os.listdir(dir):
    print f
    if f == "GM___17_.CIF":
        continue
    file = open(os.path.join(dir,f))
    route = {}
    header = file.readline()
    fields = {
        "file_type": (8, 1),
        "version_major": (2, 9),
        "version_minor": (2, 11),
        "file_originator": (32, 13),
        "source_product": (16, 45),
        "production_date": (8, 61),
        "production_time": (6, 69)
    }
    for (field, (length, start)) in fields.items():
        route[field] = header[start-1:start+length-1].strip()
    print route
    
    docs = []
    docdict = {}
    currentjourney = {}
    for line in file:
        #print start_date, end_date
        code = line[:2]
        #print code
        if code == "ZD":
            start_date = line[2:10]
            end_date = line[10:18]
            if withindate(start_date, end_date):
                input = True
            else:
                input = False
        elif input and code == "QS":
            if currentjourney != {}:
                currentjourney["type"] = "journey"
                currentjourney["_id"] = uuid4().hex
                docs.append(currentjourney)
                #ASNTEISNTOTAOOSNTSAOINTIE
            
            fields = {
                "term_time": (1, 37),
                "bank_holidays": (1, 38),
                "route_number": (4, 39)
            }
            journey = {}
            for (field, (length, start)) in fields.items():
                journey[field] = line[start-1:start+length-1].strip()
            journey["days"] = []
            for i in range(30,37):
                journey["days"].append(line[i-1:i])
            currentjourney = journey
        elif input and (code == "QO" or code == "QI" or code == "QT"):
            fields = {
                "s": (12, 3),
                "t": (4, 15)
            }
            stoptime = {}
            for (field, (length, start)) in fields.items():
                stoptime[field] = line[start-1:start+length-1].strip()
            
            if not "stops" in currentjourney:
                currentjourney["stops"] = []
            currentjourney["stops"].append(stoptime)
    db.update(docs)
    
