"""
ht2html Style class for creating rutherfurd.net.

Ollie Rutherfurd <oliver@rutherfurd.net>

$Id$
"""

import os
import posixpath
import sys
import time
from types import StringTypes
try:
    from cStringIO import StringIO
except IOError:
    from StringIO import StringIO

from HTParser import HTParser
from LinkFixer import LinkFixer
from Sidebar import Sidebar, BLANKCELL
from Skeleton import Skeleton


class BreadCrumbBanner:

    """
    Banner class which generates a trail of "bread crumbs"
    instead of site  links.

    It's not very efficient, but works well enough for
    my purposes.
    """

    def __init__(self, filename, rootdir):
        self.__filename = filename
        self.__rootdir = rootdir

    def get_banner(self):
        stdout = sys.stdout
        html = StringIO()
        try:
            sys.stdout = html
            self.__do_breakcrumbs()
        finally:
            sys.stdout = stdout
        return html.getvalue()

    def __do_breakcrumbs(self):
        # split filename into path elements
        chunks = self.__filename.split(os.sep)

        # prevent main section pages from including
        # a link to themselves.
        if self.__filename.endswith('index.html'):
            sub = 1
        else:
            sub = 0

        for i in range(1,len(chunks)-sub):

            # get directory name
            dirname = os.sep.join(chunks[:i])
            # check index page in directory
            filename = os.path.join(dirname, 'index.ht')
            # if index page found, use that, otherwise
            # use the name of the directory to display
            if os.path.exists(filename):
                href = filename + 'ml'
                p = HTParser(filename)
                title = p.get('title')
            else:
                href = dirname
                title = dirname.split(os.sep)[-1]

            # HACK: want a different title for homepage
            # (actual title is 'Welcome to Rutherfurd.net')
            if title.find('Welcome') > -1:
                title = 'Home'

            # get href for current link
            href = self.get_link_path(href, self.__rootdir)
            print '<a href="%(href)s">%(title)s</a>' % locals() + ' <b>&#187;</b> ',

        # get current pagename title (removing 'ml' from '.html' in file extension)
        p = HTParser(self.__filename[:-2])
        print p.get('title')

    def get_link_path(self, href, root):
        # running on windows...
        href = href.replace('\\','/')
        path = posixpath.join(root,href)
        return posixpath.normpath(path)


class RutherfurdDotNet(Skeleton, Sidebar, BreadCrumbBanner):

    """
    Style class to convert an ".ht" template to HTML for
    rutherfurd.net.
    """

    AUTHOR = 'Ollie&nbsp;Rutherfurd'
    EMAIL = 'oliver&#64;rutherfurd.net'

    def __init__(self, filename, rootdir, relthis):
        root,ext = os.path.splitext(filename)
        html = root + '.html'
        p = self.__parser = HTParser(filename, self.AUTHOR, self.EMAIL)
        self.__body = None
        self.__linkfixer = LinkFixer(html, rootdir, relthis)

        BreadCrumbBanner.__init__(self, html, rootdir)

        # Calculate the sidebar links, adding a few of our own.
        self.__d = {'rootdir': rootdir}
        p.process_sidebar()
        p.sidebar.append(BLANKCELL)
        # It is important not to have newlines between the img tag and the end
        # end center tags, otherwise layout gets messed up.
        p.sidebar.append(('http://www.jedit.org','''
<center>
<img src="http://www.jedit.org/made-with-jedit-9.png"
alt="Crafted with jEdit" border="0" width="120" 
height="40"></center>''' % self.__d))    # substitute '%(rootdir)s'
        p.sidebar.append(BLANKCELL)
        p.sidebar.append(('http://www.python.org/', '''
<center>
    <img alt="[Python Powered]" border="0"
         src="%(rootdir)s/images/PythonPowered.png"></center>
    ''' % self.__d))    # substitute '%(rootdir)s'
        self.__linkfixer.massage(p.sidebar, self.__d)
        Sidebar.__init__(self, p.sidebar)
        p.sidebar.append(BLANKCELL)
        copyright = self.__parser.get('copyright', '1999-%d' %
                                      time.localtime()[0])
        p.sidebar.append((None, '&copy; ' + copyright))
        self.__linkfixer.massage(p.sidebar)
        Sidebar.__init__(self, p.sidebar)
        # kludge!
        for i in range(len(p.sidebar)-1, -1, -1):
            if p.sidebar[i] == 'Email Us':
                p.sidebar[i] = 'Email me'
                break

        # another kludge, allow for section title as a link
        # since I'm including '%(rootdir)s in the link
        # I want that replaced with the value of rootdir
        for i in range(0, len(p.sidebar)):
            if type(p.sidebar[i]) in StringTypes:
                # substitute '%(rootdir)s'
                p.sidebar[i] = p.sidebar[i] % self.__d

    def get_title(self):
        return self.__parser.get('title')

    def get_sidebar(self):
        return Sidebar.get_sidebar(self)

    def get_corner(self):
        rootdir = self.__linkfixer.rootdir()
        return """
<center><a href="%(rootdir)sindex.html">Home</a></center>
    """ % self.__d  # substitute '%(rootdir)s'

    def get_corner_bgcolor(self):
        return '#ecebeb'

    def get_banner(self):
        return BreadCrumbBanner.get_banner(self)

    def get_body(self):
        if self.__body is None:
            self.__body = self.__parser.fp.read()
        return self.__body

    def get_lightshade(self):
        return '#ecebeb'

    def get_mediumshade(self):
        return '#7a8d9f'

    def get_darkshade(self):
        return '#8eb5c8'

    def get_stylesheet(self):
        # default stylesheet, substitute '%(rootdir)s'
        default = '%(rootdir)sdefault.css' % self.__d
        return self.__parser.get('stylesheet',default)

    def get_charset(self):
        return 'utf-8'


# :sidekick.parser=python:
# :indentSize=4:lineSeparator=\n:noTabs=true:tabSize=4:
