"""News
Compiles News since a certain date
"""

lastDate = "Sep 5, 2006"  

from SubmissionFilter import SubmissionFilter
from IMS import StringToDate,NodeToSubmission,SubFiler
from textwrap import wrap,fill
#from Filer import Filer

from optparse import OptionParser

parser=OptionParser(usage="testparser.py [options] [date]",version="%prog 1.0")

parser.add_option("-w","--word",
		action="store_true",dest="useword",default=False,
		help="Uses tabs to separate information.")


subfiler = SubFiler()

def RecentNews(argstring):
	(options,args) = parser.parse_args(argstring.split())
	MS = options.useword
	if args: date=' '.join(args)
	else:  date=lastDate
	cutoff = StringToDate(date)
	recentsubs = SubmissionFilter("-s reject -i -t")
	rejects = []
	for s in recentsubs:
		st = NodeToSubmission(subfiler.getXML(s))
		if StringToDate(st.dateback) > cutoff: rejects.append(st)
	
	recentsubs = SubmissionFilter("-s sold -i")
	sales = []
	for s in recentsubs:
		st = NodeToSubmission(subfiler.getXML(s))
		if StringToDate(st.dateback) > cutoff: sales.append(st)
	
	print "-------------------"
	print "Update since %s" % date
	print "Rejections"
	print "----------"
	Rejects = []
	longestmarket = 0
	longestname = 0
	for r in rejects:
		if hasattr(r,"note"): tempnote = r.note
		else: tempnote = ""
		
		longestmarket = max(longestmarket,len(r.market))
		longestname = max(longestname,len(r.story))
		Rejects.append((r.market,r.story,r.dateback,tempnote.strip()))
	lwidth = longestmarket+longestname+8+12
	if Rejects:
		n = 1
		for r in Rejects:
			if MS:
				print "%2d)\t%s\t%s\t%s" % (n,r[0],r[1],r[2])
				n += 1
				if r[3]:
					print fill(r[3],width=70,initial_indent="\t",subsequent_indent="\t")
			else:
				print "%2d) %s%s%s" % (n,r[0].ljust(longestmarket+2),r[1].ljust(longestname+2),r[2])
				n += 1
				if r[3]:
					print fill(r[3],width=lwidth,initial_indent="       ",subsequent_indent="       ")
			
	else:
		print "None"
	
	print "\nSales"
	print "-----"
	Sales = []
	longestmarket = 0
	longestname = 0
	for s in sales:
		if hasattr(s,"note"): tempnote = s.note
		else: tempnote = ""
		longestmarket = max(longestmarket,len(r.market))
		longestname = max(longestname,len(r.story))
		Sales.append((s.market,s.story,s.dateback,tempnote.strip()))
	lwidth = longestmarket+longestname+8+12
	if Sales:
		n=1
		for s in Sales:
			print "%2d) %s%s%s" % (n,s[0].ljust(longestmarket+2),s[1].ljust(longestname+2),s[2])
			n+=1
			if s[3]:
				print fill(s[3],width=lwidth,initial_indent="       ",subsequent_indent="       ")
	else:
		print "None"

	print "Stories in mail:", len(SubmissionFilter("-sinmail"))
	
if __name__=="__main__":
	from EasyDialogs import AskString
	#global lastDate
	ds = AskString("Update since when? (Default %s)" % lastDate)
	RecentNews(ds)

