#!/cygdrive/c/python34/python
# Used to get the recent text files for birds in ./text and ./Descriptions.
# Writes the new ones to checktext_out.html (all files changed since last run), so I can
# Put them in Firefox and copy them to Word to check for errors.
# It actually checks all files changed from today minus one day.

import pdb
import re
import subprocess
import os, datetime
import shutil
from bird_utils import ls_cmd

def astrip(line):
    line = line.rstrip('\n')
    line = line.lstrip()
    line = line.rstrip()
    return line

birds = {}
pntr = {}
text = {}
desc = {}
bird_text = {}
f_old_date = 'data/checktext_old.date'
f_last_date = 'data/checktext.date'

	# get a ls of the text/Description files showing the date in number format
#pdb.set_trace()
ls1 = ls_cmd('--full-time', '../text/*.txt')
ls2 = ls_cmd('--full-time', '../Descriptions/*.txt')
tx_files = ls1 + ls2

	# get the last time stamp for running this program so I only pick up new text files
	# the next time I run it.
text_f = open(f_last_date)
in_date = text_f.readline()
text_f.close()
in_date = astrip(in_date)
in_date = in_date.replace('-','')
last_date = int(in_date)
	# do I want to update the date file
ans = input('Update the date file to the current time: ')
flag = 0
if ans == 'Y' or ans == 'y':
    flag=1

	# now out the file to write the contents of the .txt files to if
    	# the modification for that file is greater than the last time
    	# I ran this program.  Output is written to out.html which I can
    	# take into Word to check for grammar and spelling errors.
outfile = open('checktext_out.html', 'w')
outfile.write ('<html>\n<body>\n')
print ('----Bird text files that I wrote to out.html')
for line in tx_files:
    if len(line) < 1: continue
    fields = line.split()
    tmp = re.sub('-','', fields[5])
    file_date = int(tmp)
    if file_date >= last_date:
        print (line)
        infile = open(fields[-1])
        for fline in infile:
            outfile.write(fline)
    # If I wrote any bird text file to out.html, update the date
    # that I last used this program.
if (flag):
    #pdb.set_trace()
        # now write out the time for later checking
    shutil.copyfile(f_last_date, f_old_date)
    	# Now update the time to start checking next time.  it is today - 1 day.  I do this
	# because I had trouble getting PST time and I rather recheck a few files than not
	# get some checked
    current_t = datetime.date.today()
    one_day = datetime.timedelta(days=1)
    time_res = current_t - one_day
    	# Now convert to a string and then get rid of T and other stuff
    time_res = time_res.isoformat()		# convert from date class to a string
    out_date = open(f_last_date, 'w')
    out_date.write(time_res)
    out_date.close()
    
outfile.write ('</html>\n</body>\n')
outfile.close()
