#!/usr/bin/env python

import os
import sys
import shutil
import fileinput
import markdown2

from optparse import OptionParser
from jinja2 import Environment, FileSystemLoader, PackageLoader

# Capture our current directory
THIS_DIR = os.path.dirname(os.path.abspath(__file__))

#
# Usage example
#
def usage_helper():
	return "Usage of static.py site generator:\n \
	\n\
	$ static --create /home/user/path_to_new_site\n\
	or\n\
	$ static -c /home/user/path_to_new_site\n"

#
# Get post header
#
def get_post_header(post):
	# read file and get first string
	return open(post, 'r').readline()

# Main loop
def main():
	usage = 'static [options]'
	parser = OptionParser(usage)
	# parse options
	parser.add_option('-c', '--create', action = 'store_true', help = 'create new site template', default = False)
	parser.add_option('-b', '--build',  action = 'store_true', help = 'build site with content', default = False)
	# Get options and args
	(options, args) = parser.parse_args()

	#
	# create site template
	#
	if options.create and len(args) == 1:
		# new site directory
		site_dir = args[0]
		"""
		start to create new site template
		"""
		# create directory for new template
		if not os.path.exists(site_dir):
			os.makedirs(site_dir)
		else:
			# remove directory
			shutil.rmtree(site_dir)

		# create css directory
		os.makedirs(site_dir + '/css')
		# create js directory
		os.makedirs(site_dir + '/js')
		
		# copy twitter css to css directory
		shutil.copy2('res/bootstrap/css/bootstrap.min.css', site_dir + '/css')
		# copy twitter js to js directory
		shutil.copy2('res/bootstrap/js/bootstrap.min.js', site_dir + '/js')
		# create posts directory
		os.makedirs(site_dir + '/posts')

		# copy test.md
		shutil.copy2('res/README.md', site_dir + '/posts/')
		# copy index.html file
		shutil.copy2('res/index.html', site_dir)
		
		# return
		return 0
	#
	# Build site
	#
	elif options.build and len(args) == 1:
		# create jinja environment
		jinja_env = Environment(loader = FileSystemLoader(THIS_DIR), trim_blocks=True)
		"""
			Get header title
		"""
		sys.stdout.write('Input site header text: ')
		site_header = raw_input()

		"""
			Do you need comments with DISQUS
		"""
		sys.stdout.write('do you need comments with disqus y/n: ')
		disqus = raw_input()

		if disqus == 'y':
			# get short name
			sys.stdout.write('Your disqus short name is: ')
			disqus_short_name = raw_input()

		"""
			Main part
		"""

		# site directory
		site_dir = args[0]
		# headers with file names list
		post_headers_list = []
		# post with link list
		post_links_list = []
		# Get all posts lists
		posts = [f for f in os.listdir(site_dir + '/posts/') if os.path.isfile(os.path.join(site_dir + '/posts/',f))]
		# Get list of all posts and headers
		for post in posts:
			post_header = get_post_header(site_dir + '/posts/' + post)
			post_headers_list.append((post, post_header))
			post_links_list.append((os.path.splitext(post)[0] + '.html', post_header))

		"""
		Genearte main page with posts
		"""
		# fill index html template with content
		posts_list = jinja_env.get_template('res/posts.html').render(title = site_header, header_title = site_header, posts = post_links_list)
		# write to index.html posts list	
		open(site_dir + '/index.html', "w").writelines(posts_list)
		
		"""
		Generate posts
		"""
		for (post, header) in post_headers_list:
			# file line counter
			line_count = 0
			# new html page
			html_page_path = site_dir + '/' + os.path.splitext(post)[0] + '.html'
			# create html page for all posts
			shutil.copy2('res/index.html', html_page_path)

			# read post and convert it to markdown
			post_in_markdown = markdown2.markdown(open(site_dir + '/posts/' + post).read())

			"""
				fill html page
			"""
			# check disqus need or not
			if disqus == 'y':
				# render template
				post_content = jinja_env.get_template('res/index.html').render(title = header, header_title = site_header, 
					note = post_in_markdown, disqus = 1, disq_short_name = '\'' + disqus_short_name +'\'')
				# write file content
				open(html_page_path, "w").writelines(post_content)
			else:
				# render template
				post_content = jinja_env.get_template('res/index.html').render(title = header, header_title = site_header, 
					note = post_in_markdown, disqus = 0, disq_short_name = '')
				# write file content
				open(html_page_path, "w").writelines(post_content)		
	else:
		# Error log
		print "Wrong options \n" + str(usage_helper())
		# return
		return 1		
# start
if __name__ == '__main__':
    main()
