#!/usr/bin/env python
# -*- coding: utf-8 -*-
r"""
sage-sws2rst
============

Translate a Sage worksheet file (.sws) into an rst file.

Usage::

    sage --sws2rst [-h] <source sws file>

Print the help message::

    sage --sws2rst -h

EXAMPLES::

    sage --sws2rst file.sws

The sws file should be in the current directory; using an
absolute path will result in an error.

AUTHOR:

    - Pablo Angulo (January 2011): Initial version
    - Karl-Dieter Crisman (June 2012): Documentation
      and minor refinements
"""
#############################################################################
#       Copyright (C) 2011 Pablo Angulo
#  Distributed under the terms of the GNU General Public License (GPL)
#  The full text of the GPL is available at:
#                  http://www.gnu.org/licenses/
#############################################################################
import sys
import tarfile
import os
import shutil
import codecs
import tempfile
from sagenb.misc.worksheet2rst import worksheet2rst

from optparse import OptionParser


# function where everything happens
def process_sws(file_name):

    sws_file = tarfile.open(file_name, mode='r:bz2')
    #TODO: python complains about using tempnam, but I don't
    #know hot to fix it or see any danger
#    tempname = os.tempnam('.')
    tempname = os.path.join(tempfile.gettempdir(), file_name)
    sws_file.extractall(tempname)
    base_name = os.path.split(os.path.splitext(file_name)[0])[1]
    base_name_clean = base_name.replace(' ','_')

    #Images
    images_dir = base_name_clean + '_media'
    if not os.path.exists(images_dir):
        os.mkdir(images_dir)

    #"data" dir
    data_path = os.path.join(tempname,'sage_worksheet','data')
    if os.path.exists(data_path):
        for image in os.listdir(data_path):
            try:
                shutil.move(os.path.join(data_path, image), os.path.join(images_dir, image.replace(' ','_')))
            except shutil.Error:
                pass

    #cells
    cells_path = os.path.join(tempname,'sage_worksheet','cells')
    if os.path.exists(cells_path):
        for cell in os.listdir(cells_path):
            cell_path = os.path.join(cells_path, cell)
            for image in os.listdir(cell_path):
                if os.path.isfile(os.path.join(cell_path, image)):
                    shutil.copy2(os.path.join(cell_path, image),
                                 os.path.join(images_dir, 'cell_%s_%s'%(cell,image)))
                # could be Jmol image directory - code for future
                #elif os.path.isdir(os.path.join(cell_path, image)):
                #    if image == '.jmol_images':
                #        for jmolimg in os.listdir(os.path.join(cell_path, image)):
                #            shutil.copy2(os.path.join(cell_path, image, jmolimg),
                #                     os.path.join(images_dir, 'cell_%s_%s'%(cell,jmolimg)))

    #read html file, parse it, write rst file
    file = codecs.open(os.path.join('.',tempname,'sage_worksheet','worksheet.html'),
                          mode='r',
                          encoding='utf-8')
    html_text = file.read()
    file.close()
    rst_text = worksheet2rst(html_text, images_dir = images_dir)
    rst_file = base_name_clean + '.rst'
    out_file = codecs.open(rst_file, mode='w',
                  encoding='utf-8')
    out_file.write(rst_text)
    out_file.close()
    print "File at "+rst_file
    print "Image directory at "+images_dir

    shutil.rmtree(tempname)


# Set the parser
usage = r"""

    sage -sws2rst [options]  <source sws file> ...

Translate a Sage worksheet file (.sws) into an reStructuredText
(.rst) file.  At least one sws file argument is required; all sws
files will be parsed and translated.  Spaces in the names of the
worksheet will be converted to underscores.

Examples:

    sage --sws2rst file.sws
    sage --sws2rst file1.sws file2.sws file3.sws
    sage --sws2rst -h # this help message prints
    sage --sws2rst --sphinxify # information about how to use
                               # Sphinx to compile your rst file

Remark:

    The sws file(s) should be in the current directory; using an
    absolute path will result in an error."""

sphinxify_text = r"""

Once you have made your rst file, what can you do with it?

If this is a file which is likely to become part of the Sage
standard documentation, you will want to edit the appropriate
file in $SAGE_ROOT/devel/sage/doc to include your file, or
simply include your file as appropriate.

However, you may simply want to make great-looking documentation
for some other purpose out of your worksheet.  The following
steps are one way to do so.

 - Assume that the generated .rst file is ``My_Project.rst``.
 - Make a folder somewhere convenient to compile in, say, ``MyProject``.
 - Then move your .rst file into that folder, and cd into it.
 - Now the key is to use Sage's shell to run Sphinx on it! Run ``sage --sh``.
 - Then type ``sphinx-quickstart`` and follow the instructions in the
   Sphinx tutorial [1]_. You will probably want to choose to render math
   with MathJax [2]_, but you can accept the defaults for the other options.
 - Finally, edit ``index.rst`` by adding ``My_Project`` in the table of
   contents, as detailed in the Sphinx tutorial [3]_.
 - If you now type ``make html`` you should get a beautiful-looking web page
   in ``_build/html``. If you did not have a header at the top of your worksheet,
   you may get an error, but you can ignore this.

REFERENCES:

.. [1] First Steps with Sphinx,
   http://sphinx.pocoo.org/tutorial.html
.. [2] MathJax,
   http://www.mathjax.org/
.. [3] Defining Document Structure, First Steps with Sphinx,
   http://sphinx.pocoo.org/tutorial.html#defining-document-structure"""

parser = OptionParser(usage=usage)
parser.add_option("--sphinxify",
                  action="store_true", dest="sphinxify",
                  help="Print information about how to use Sphinx to compile your rst file, then exit.")
(options, args) = parser.parse_args()

# Parse option
if options.sphinxify:
    print sphinxify_text
    sys.exit(0)

# Parse arguments
if len(args) < 1:
    parser.print_usage()
    sys.exit(1)

for file_name in args:
    print "Processing "+file_name
    try:
        process_sws(file_name)
    except Exception as e:
        print "Unable to process file ('%s')" % file_name
        print "Error message: %s" % e
        print "Exiting."
        sys.exit(1)
