#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
"""
    Coconuts example for creating wikipages from html pages

    :copyright: 2010-2013 by ReimarBauer
    :license: GNU GPL, see COPYING for details.
    
    2018-03-04 Rudolf Reuter, modified for Typo3 source
"""

import re  # for regex compile

from Coconuts import log
log.load_config('coconutslogging.conf')
logging = log.getLogger(__name__)

import os
import sys

import urlparse
from settings import Config
from Coconuts.caching.Caching import Caching
#print('\n'.join(sys.path))  # RR for debug
from Coconuts.utils import transform_encoding
from Coconuts.convertor import Convert
from Coconuts.xmlrpc import XmlRpc, SendContent
from Coconuts.parser import Parser, RegexError, TidyLibError
from xmlrpclib import expat


def _pagename(encoding, prefix, title, hash_digest):
    return title


class html2wiki(SendContent.SendContent):
    """
    Coconuts html2wiki

    example which writes html pages from given urls
    as wiki markup to a wiki.

    :copyright: 2010 by ReimarBauer
    :license: GNU GPL, see COPYING for details.
    """
    SendContent._pagename = _pagename

    def run(self):
        """
        creates the wiki pages
        """
        s_urls = self.urls
        self.cfg.wikipageprefix = ""
        for link in s_urls:
            logging.debug(link)
            urlp = urlparse.urlparse(link)
            netloc = urlp.netloc
            pagename = link.split(netloc)[1].lstrip('/').split('.htm')[0]
            names = pagename.split('/')
            names = [name.title() for name in names]
            pagename = '/'.join(names)
            
            # adopt wiki page name prefix
            pos = pagename.find("=")                    # RR
            pagename = pagename[pos+1:]                 # RR, extract real pagename
            pagename = "RudisFlugis" + pagename         # RR, add prefix
            #pagename = "RudisFlugisModell" + pagename  # RR, add prefix
            
            html_page = Caching(self.cfg, link)
            text = html_page.read()
            parser = Parser(self.cfg, text)
            moinmoin = Convert(self.cfg.expatlog_dir)
            try:
                # if that is too much broken we don't need to convert at all
                html_fragment = parser.html_fragment
            except (RegexError, TidyLibError), err:
                logging.debug("%s %s" % (link, err))
                continue
            #print(html_fragment)  # RR for program analysis
            try:
                successful, wiki_text = moinmoin.convert_in_moin_markup(parser.title, html_fragment)
            except (expat.ExpatError, TidyLibError), err:
                logging.debug("%s %s" % (link, err))
                continue
            print(pagename)  # RR for debug
            
            # Add moin wiki page header to body text
            t1 = '#format wiki\n'
            t2 = '#language  de\n'
            t3 = '||<tablestyle="float: right; margin: 0px;"style="padding: 0.5em; '
            t4 = 'border: 0px none; font-size: 100%;"><<TableOfContents>> ||\n'
            wiki_text = t1 + t2 + t3 + t4 + wiki_text + '\n\n'
            #print(parser.image_urls)  # RR for program analysis
            
            # get picture file names list
            lstPics = parser.image_urls 
            print(lstPics)  # RR for debug

            # add picture attachment link list to wiki text
            t1 = '||<tablestyle="float: right;">[[attachment:'
            t2 = '|{{attachment:'
            t3 = '|attachment:'
            t4 = '|width="320"}}]] ||\n'
            for i in range(len(lstPics)):  # RR build attachment refs
                pic = lstPics[i]
                wiki_text = wiki_text + t1 + pic + t2 + pic + t3 + pic + t4
                
            # add wiki footer to wiki text
            t1 = '=== Kontakt Email ===\n'
            t2 = 'Geben sie bitte ihre Email Adresse ein, wenn sie eine Antwort erwarten\n\n'
            t3 = "/!\ '''Die eingegebene Email Adresse wird nicht veroeffentlicht, oder weitergegeben.'''\n"
            t4 = '<<AddComment>>\n\n'
            t5 = '=== Liste der Seiten in dieser Kategorie ===\n'
            t6 = '<<FullSearch(category:CategoryRudisFlugis)>>\n\n'
            t7 = '----\n'
            t8 = 'Gehe zurueck zu CategoryRudisFlugis oder StartSeite\n'
            wiki_text = wiki_text + t1 + t2 + t3 + t4 + t5 + t6 + t7 + t8
            
            # send wiki text to moin wiki via XMLRPC (Remote Procedure Call)
            self.xmlrpc.send_page(pagename, wiki_text)  
            #print(parser.image_urls)  # RR for program analysis
            #print(wiki_text)          # RR for program analysis
            
            # prepare list of picture URL's
            for i in range(len(lstPics)):  # build URL
                lstPics[i] = "http://192.168.17.72/cms/uploads/pics/" + lstPics[i]
            #print(lstPics)  # RR for debug
            
            # Send pictures to moin wiki as an attachment
            self.images_send(lstPics, parser.encoding, pagename, "")

if __name__ == '__main__':
    logging = log.getLogger(__file__)
    logging.info('start')
    cfg = Config()
    xmlrpc_init = XmlRpc(cfg.wikiurl, cfg.username, cfg.password)
    cp2wiki = html2wiki(cfg, xmlrpc_init)
    cp2wiki.run()
    logging.info('done')

