#! /usr/bin/env python
# -*- coding: utf-8 -*-
#####################      A U T H O R        ##########################
#   Copyright (C) 2010 Jack Desert                                     #
#   jackdesert556@gmail.com                                            #
#   http://www.LetsEATalready.com                                      #
#                                                                      #
######################     L I C E N S E      ##########################
#   This program is free software; you can redistribute it and/or      #
#   modify it under the terms of the GNU General Public License        #
#   as published by the Free Software Foundation; either version 2     #
#   of the License, or any later version.                              #
#                                                                      #
#   This program is distributed in the hope that it will be useful,    #
#   but WITHOUT ANY WARRANTY; without even the implied warranty of     #
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      #
#   GNU General Public License for more details.                       #
#                                                                      #
#   You should have received a copy of the GNU General Public License  #
#   along with this program; if not, write to                          #
#                                                                      #
#   the Free Software Foundation, Inc.,                                #
#   59 Temple Place - Suite 330,                                       #
#   Boston, MA   02111-1307, USA.                                      #
#                                                                      #
########################################################################

# LyXHTML(.xhtml) --> clipboard(.html)
# This python script takes an XHTML file as an input,
# And copies the HTML to your clipboard for inserting into blog posts
# Here is an article describing how it came about
# http://letseatalready.com/2010/03/08/lyxblogger-blogging-with-lyx/
# Author: Jack Desert
# Author's Website: http://LetsEATalready.com
# Date: March 14, 2010
# To use LyxBlogger, save
#  this file as /usr/bin/lyxblogger, make it executable with
#  $ chmod +x /usr/bin/lyxblogger
#  Install the following Dependencies:
#  elyxer (version 0.42 or later required for '--raw' option
#  xclip 0.11 or later (earlier versions do not support utf-8)
#  Then invoke
#  $ lyxblogger my_new_post.lyx

import sys, os, re
TEMP_DIR = '.temp_latex_665917/'
INPUT_COPY = 'copy_of_input_file.xhtml'
error_msg = ''
input_file = sys.argv[1]    # Incoming file name
# Make sure input file ends in .lyx
if(input_file[-6:] == '.xhtml'):
    # Make a temporary directory and work from there
    if (os.path.exists(TEMP_DIR) == False):
        os.system('mkdir %s' % (TEMP_DIR))
    os.system('cp %s %s%s' % (input_file, TEMP_DIR, INPUT_COPY))
    input_path = TEMP_DIR + INPUT_COPY
    OUTPUT_FILE = input_path[0:-6] + '.xhtml'
    if(os.path.exists(input_path)):
        pass
    else:
        error_msg += 'Error: input_path %s does not exist/n/n' % (input_path)
        raise Exception(error_msg)
else:
    error_msg += 'Error: Input file must be of type .xhtml/n/n'
    raise Exception(error_msg)

# Read data from file
f = open(input_path, 'r')
html = f.read()
f.close()

# Strip off the beginning and ending tags
START_TAG = '<body>'
END_TAG = '</body>'
if (START_TAG in html):
    html = html.partition(START_TAG)[2]
html = html.partition(END_TAG)[0]

# Reinvoke <code> and </code> tags from their escape sequence counterparts
html = html.replace('&lt;code&gt;', '<code>')
html = html.replace('&lt;/code&gt;', '</code>')

# Remove Arrows from footnotes and margin notes
html = html.replace('[→', '[')
html = html.replace('→]', ']')

# Strip off cut material using the flag '#! CUT MATERIAL'
CUT_FLAG = '#! CUT MATERIAL'
exp = re.compile('<div class="\D{1,}"><a id=\'magicparlabel-\d{1,}\' />\n' + CUT_FLAG)
srch_obj = exp.search(html)
if(srch_obj):
    start_index = srch_obj.start()
    print('this expression found at location: ' + str(start_index))
    html = html[0:start_index]
else:
    print 'No Match found for %s!' % (CUT_FLAG)

# Add tags so that the wordpress plugin 'html-raw' works
html = '<!--start_raw-->' + html + '<!--end_raw-->'

#~ # Write data to file
f = open(OUTPUT_FILE, 'w')

if(error_msg == ''):
    f.write(html)
else:
    f.write(error_msg)
    print '\n\nERROR: \n\nPlease Try Again\n\n'

f.close()
os.system('xclip -i -selection clipboard %s' % (OUTPUT_FILE))

# Clean up
if (os.path.exists(TEMP_DIR)):
    os.system('rm -r %s' % (TEMP_DIR))

