#!/usr/athena/bin/python

from socket import *
import time
import os
import string
import sys

filename = "/afs/athena.mit.edu/activity/r/random-desk/Logs/original-logs/log-"

seconds_per_day = 60 * 60 * 24

def get_filename():
	seconds = time.time()
	local_time = time.localtime(seconds)
	fmt = "%m%d%y"

	# struct_time[3] = tm_hour, range [0, 23]
	if local_time[3] < 6:
		# should pretend it's the previous day if before 6am
		# sec/day = 60 sec/min * 60 min/hr * 24 hr/day
		seconds -= seconds_per_day
		local_time = time.localtime(seconds)
		
	# Set back time the number of days to get to the date of the last Monday
	# struct_time[6] = tm_wkday, range [0, 6], Monday is 0
	seconds -= local_time[6] * seconds_per_day
	local_time = time.localtime(seconds)
	
	# filename we use is log-start-end, where start and end are the
	# starting and ending dates of the week
	weekstart = time.strftime(fmt, local_time)
	weekend = time.strftime(fmt, time.localtime(seconds + 6 * seconds_per_day))
	return "".join([filename, weekstart, "-", weekend])

def make_message(logtype):
	temp = string.join([logtypes[logtype], os.environ['USER']])
	li = sys.argv[2:]
	for x in range(len(li)):
		temp = string.join([temp, li[x]])
	return string.join([temp, '\n'])

def require_till(logtype):
	if len(sys.argv) < 3:
		print "\nError: Need to record till!"
		sys.exit()
	try:
		till = float(sys.argv[2])
	except:
		print "\nError: Till not a valid number!"
		sys.exit()
	return make_message(logtype)

def list_log(logtype):
	search = ""
	try:
		search = sys.argv[2]
	except:
		search = os.environ['USER']
	grepcmd = "grep \"" + search + "\" " + get_filename()
	output = "\n"
	for f in os.popen(grepcmd).readlines():
		output += f
	print output

def list_shifts(logtype):
	search = ""
	try:
		search = sys.argv[2]
	except:
		search = os.environ['USER']
	grepcmd = "grep \"" + search + "\" /afs/athena.mit.edu/activity/r/random-desk/shiftlist.txt"
	output = "\n"
	for f in os.popen(grepcmd).readlines():
		output += f
	print output

def print_help():
	print ""
	print "Syntax is generally 'desklog [command] [till] [comments]'"
	print "  Commands are:"
	print "    For logging desk shifts (must include till for open, out, and close):"
	print "      open       For starting a shift where you had to open desk."
	print "      in         For starting a shift where you didn't have to open desk."
	print "      out        For ending a shift when you didn't have to close desk."
	print "      close      For ending a shift where you had to close desk."
	print "    For mail shifts:"
	print "      mailstart  For starting a mail shift."
	print "      mailend    For ending a mail shift.  Include comments if desired."
	print "    For nightwatch shifts:"
	print "      nightstart For starting a nightwatch shift."
	print "      nightend   For ending a nightwatch shift."
	print "    Other:"
	print "      till       For logging a change in the desk till."
	print "      comment    For logging any sort of general comments."
	print "      list       For listing all your logged hours in the current week."
	print "                 (Also acts like grep if you give it arguments.)"
	print "      shifts     For listing someone's scheduled shifts for the week."
	print "                 (Put the desk initials or a time in the comment.)"
	print ""

fnlist = { 'open'      : require_till,
	   'in'        : make_message,
	   'out'       : require_till,
	   'close'     : require_till,
	   'mailstart' : make_message,
	   'mailend'   : make_message,
	   'nightstart': make_message,
	   'nightend'  : make_message,
	   'till'      : require_till,
	   'comment'   : make_message,
	   'list'      : list_log,
	   'shifts'    : list_shifts }

logtypes = { 'open'      : ' SHIFT OPEN ',
	     'in'        : ' SHIFT START',
	     'out'       : ' SHIFT END  ',
	     'close'     : ' SHIFT CLOSE',
	     'mailstart' : ' MAIL START ',
	     'mailend'   : ' MAIL END   ',
	     'nightstart': ' NIGHT START',
	     'nightend'  : ' NIGHT END  ',
	     'till'      : ' TILL CHANGE',
	     'comment'   : ' COMMENT    ' }

message = ''
try:
	message = fnlist[string.lower(sys.argv[1])](string.lower(sys.argv[1]))
except:
	print_help()
	sys.exit()

if string.lower(sys.argv[1]) == "list" or string.lower(sys.argv[1]) == "shifts":
	sys.exit()

serverHost = '18.181.0.51' # linerva.mit.edu
#serverHost = '18.181.0.46' # scripts.mit.edu
serverPort = 9391

sockobj = socket(AF_INET, SOCK_STREAM)
sockobj.connect((serverHost, serverPort))

data = sockobj.recv(1024)
if data != 'okay':
	print data
	sockobj.close()
	sys.exit()
else:
	for line in [message]:
		sockobj.send(line)
		data = sockobj.recv(1024)
		print '\nLogged:\n', data

sockobj.close()
