#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
from random import *
import nltk
import time
from random import shuffle

# Year is name of the containing folder

year = '1941'
now = time.strftime("%Y-%m-%d_%H:%M:%S")
# filename = year+'_'+now+'.txt'
filename = year+'_'+now+'.tex'

random_author = ""
duo = []
author_texts = []
texts = []

spring_chapter=[]
summer_chapter=[]
autumn_chapter=[]
winter_chapter=[]

spring_select = []
summer_select = []
autumn_select = []
winter_select = []

def writetoLog(content):
		try:
			logfile = open(filename, "a")
			try:
				logfile.write(content)
			finally:
				logfile.close()
		except IOError:
			pass

# Print header for ConText

header = open('header.txt', 'r')
header = header.read()
writetoLog(header)

# Make list of authors based on folder names

authors =  os.listdir(year)

# Select a random duo of two authors (no repeats), and select one random text per author

i = 0
while i < 2:
	if authors != []:
		pos = randrange(len(authors))
		random_author = authors[pos]
		authors[pos] = authors[-1]
		del authors[-1]
		duo.append(random_author)
		i += 1

for author in duo:
	path = year+"/"+author
	author_texts = os.listdir(path)
	pos = randrange(len(author_texts))
	random_text = path+"/"+author_texts[pos]
	texts.append(random_text)

# Seasonal keywords

spring = ['birth','butterfly','flower','energy', 'breakthrough', 'sprawl', 'toddler', 'grow', 'plasticine', 'toy', 'hope', 'teenager', 'puberty', 'adolescence', 'sneakers', 'acne', 'pimple', 'jitters', 'first time', 'slang', 'verdant', 'leafy', 'juvenile', 'inexperienced', 'girlish', 'young', 'verginal', 'ingenuous', 'naive', 'innocent', 'launch', 'genesis', 'youth', 'vibration', 'dynamic', 'dynamism', 'vibrance', 'empowerment', 'enhancement', 'innovation', 'invention', 'play', 'await', 'blessing', 'fresh', 'small', 'spring', 'morning', 'sunrise', 'dawn']

summer = ['sun', 'heat', 'growth','expansion', 'develop', 'unfold', 'radiance', 'attempt', 'succeed', 'stumble', 'bloom', 'blossom', 'light', 'persistence', 'grace', 'mature' , 'strength' , 'method', 'serendipity', 'success', 'summit', 'zenith', 'glory', 'grandeur', 'splendor', 'belle epoque', 'power', 'bright', 'ripe', 'summer', 'rose', 'harmony', 'midday', 'full', 'birds', 'fashion', 'class', 'winner', 'victory', 'triumph', 'realization', 'diamond', 'precious', 'excitement', 'gold', 'beauty', 'fire']

autumn = ['leaves', 'decay', 'grey', 'gray','age','generation', 'calmness', 'sofa', 'pipe', 'mist','memory', 'remembrance', 'nostalgia', 'picture', 'cigar', 'painting', 'museum','indian summer',  'peace', 'sharing', 'teaching', 'harvest', 'slow', 'stiff', 'waste', 'autumn', 'sunset', 'dusk', 'evening', 'shadow', 'gloaming', 'twilight', 'feather', 'quiet', 'serenity', 'stillness', 'tranquility', 'rest', 'relaxed', 'silence', 'library', 'thought', 'experience', 'wise', 'wisdom', 'reflective', 'literate', 'serious']

winter = ['death', 'ice', 'cold','illness', 'death', 'ruin', 'decay', 'medicine', 'pus', 'infection', 'virus', 'nurse', 'hospital','funeral', 'coffin', 'soil', 'rat', 'skull', 'bones', 'skeleton','humus', 'transformation', 'symbiosis', 'seed', 'egg', 'offspring', 'sprout', 'pain', 'deteriorate', 'regress', 'retrogress', 'return', 'alter', 'change', 'metamorphose', 'modify', 'mutate', 'transfigure', 'transform', 'transmute', 'winter', 'snow', 'night', 'hell', 'heaven', 'earth','archives', 'replica', 'sorrow', 'grief', 'old']

# Select 20 random keywords from seasonal lists

i = 0
while i < 10:
	if spring != []:
		pos = randrange(len(spring))
		word = spring[pos]
		spring[pos] = spring[-1]
		del spring[-1]
		spring_select.append(word)
		i += 1

i = 0
while i < 10:
	if summer != []:
		pos = randrange(len(summer))
		word = summer[pos]
		summer[pos] = summer[-1]
		del summer[-1]
		summer_select.append(word)
		i += 1

i = 0
while i < 10:
	if autumn != []:
		pos = randrange(len(autumn))
		word = autumn[pos]
		autumn[pos] = autumn[-1]
		del autumn[-1]
		autumn_select.append(word)
		i += 1

i = 0
while i < 10:
	if winter != []:
		pos = randrange(len(winter))
		word = winter[pos]
		winter[pos] = winter[-1]
		del winter[-1]
		winter_select.append(word)
		i += 1

# Open all files and do basic cleanup

for source in texts:
	text = open(source, 'r')
	text = text.read()
	text = text.replace("\r\n", " ")
	text = text.replace("\r", " ")
	text = text.replace("\n", " ")
	text = text.replace("  ", " ")

# Split text into sentences with help of nltk

	sent_tokenizer=nltk.data.load('tokenizers/punkt/english.pickle')
	sentences = sent_tokenizer.tokenize(text)

# Split each element of sentences into list of words

	for sentence in sentences:
		list = sentence.split(" ")

		for word in list:

# Check if sentence contains a seasonal keyword, generate fake paragraps and combine sentences into chapters

			i = 0

			if word in spring_select:
				i += 1
				sentence = sentence+' '
				if i == randint(1,6):
					sentence = sentence+"\n\n"
					i = 0
		 		spring_chapter.append(sentence)

		 	if word in summer_select:
				i += 1
				sentence = sentence+' '
				if i == randint(1,6):
					sentence = sentence+"\n\n"
					i = 0
		 		summer_chapter.append(sentence)

		 	if word in autumn_select:
				i += 1
				sentence = sentence+' '
				if i == randint(1,6):
					sentence = sentence+"\n\n"
					i = 0
		 		autumn_chapter.append(sentence)

		 	if word in winter_select:
				i += 1
				sentence = sentence+' '
				if i == randint(1,6):
					sentence = sentence+"\n\n"
					i = 0
		 		winter_chapter.append(sentence)
		
# Mix sentences

shuffle(spring_chapter)
shuffle(summer_chapter)
shuffle(autumn_chapter)
shuffle(winter_chapter)

# Open file and write book

author_duo = (str(duo[0])+' & '+str(duo[1])).replace("_", " ")

writetoLog('\chapter{The Death of the Authors\crlf\crlf\n')
writetoLog(author_duo+'\n')
writetoLog('& Their Return to Life in Four Seasons\crlf}\n')
writetoLog('A Constant Remix\n')

# Print chapter

writetoLog('\n\section{Spring}\n')
writetoLog('\setuppagenumber[state=start]')

# Open file and add sentences

for sentence in spring_chapter:

	writetoLog(sentence)

# Print chapter

writetoLog('\n\section{Summer}\n')

# Open file and add sentences

for sentence in summer_chapter:

	writetoLog(sentence)

# Print chapter

writetoLog('\n\section{Autumn}\n')

# Open file and add sentences

for sentence in autumn_chapter:

	writetoLog(sentence)

# Print chapter

writetoLog('\n\section{Winter}\n')

# Open file and add sentences

for sentence in winter_chapter:

	writetoLog(sentence)

# Open file and add sources

writetoLog("\n\section{Colophon}")
writetoLog("Sources:\crlf\n")

for text in texts:
	credits = open(text,'r').readlines()[:1]

	for credit in credits:

#ConText escaping:

		credit = credit.replace("#", "{\#}")
		writetoLog(credit+'\crlf\n ')

writetoLog('\nThis book was generated on '+now+' from sources available in the Public Domain as of '+str(int(year) + 71)+', 70 years after the death of '+author_duo+'.\n\crlf\crlf\nRead more at:\crlf\nwww.publicdomainday.org\crlf\nwww.constantvzw.org/publicdomainday')

writetoLog('\n\stoptext\n')

print filename

import subprocess
subprocess.call(["/usr/bin/context", "/var/www/publicdomainday/" + filename])
