import os, sys
import numpy as np;from pandas import *
from datetime import timedelta
#import datetime

#To run, it needs two things: the path to the file nodes.each.timestep.txt, and the path to the folder with all the station files in it.  I assumed that the station files would be in their own folder. 
#The script will create a folder in your current folder called nodes, and put one file for each station in there containing the daily som mappings. 
#USAGE: python DateToNode.Test3.py daily.node.mapping.txt ../../Stations.99ile

def stringTime(date):
	return "%04d%02d%02d" % (date.year, date.month, date.day)

#def stringTime(date):
#	return "%02d%02d%04d" % (date.day, date.month, date.year)

#Start date of the data
date0=datetime(1998, 01, 01)

#path to som file
som_file = open(sys.argv[1], "r")
nodes = []
for line in som_file.readlines():
	if line.strip() == "":
		continue
	nodes.append(int(line))
date_range = DateRange(start=datetime(1998, 01, 01), end=datetime(2009, 12, 31), offset=DateOffset(days=1))
#date_range = DateRange(start=datetime(01, 01, 1998), end=datetime(31, 12, 2009), offset=DateOffset(days=1))
fillers = ["_" for x in range(0, len(date_range))]
node_mappings = Series(fillers, index=date_range)
index = 0

for x in range(0, len(date_range)):
	node_mappings[x] = nodes[index:index]
	index += 1
	
# path to directory containing station files
dirlist = sorted(os.listdir(sys.argv[2]))

if not os.path.exists("./StationMapping/"):
	os.makedirs("./StationMapping")
for entry in dirlist:
	if entry[-3:] != "txt":
		continue
	infile = open(os.path.join(sys.argv[2], entry), "r")
	
	outfile = open("./StationMapping/" + entry[:-1] + "_nodes.txt", "w")
	infile.readline()
	for line in infile.readlines():
		if line.strip() == "":
			continue
		temp = line.strip().split(",")
		date = datetime(int(temp[0]), int(temp[1]), int(temp[2]))
		if date not in node_mappings:
			continue
#		outfile.write("%s,%d,%d,%d,%d\n" % (stringTime(date), node_mappings[date][0], node_mappings[date][1], node_mappings[date][2], node_mappings[date][3])) #This writes out the full date
		outfile.write("%s,%d,%d,%d,%d\n" % ((date-date0).days, node_mappings[date][0], node_mappings[date][1], node_mappings[date][2], node_mappings[date][3])) #This writes out the number of days since 01jan1998 for use in grads
	outfile.close()
