import datetime
import os
from xml.dom.minidom import parse, parseString
from dynastie.generators.generator import DynastieGenerator, StrictUTF8Writer
from dynastie.generators.index import Index
from django.db import models

class Post(Index):

    def _createPost(self, post, dom, post_elem, root):
        self.createPost(post, dom, post_elem, root)
        post_nodes = dom.getElementsByTagNameNS(self.URI, "post")
        post_elem = post_nodes[0]
        post_elem.parentNode.removeChild(post_elem)

        title_nodes = dom.getElementsByTagName("title")

        # Set title to be title's post
        for node in title_nodes:
            if node.hasChildNodes():
                node.removeChild(node.childNodes[0])
            node.appendChild(dom.createTextNode(post.title))

    def generate(self, blog, src, output):
        from dynastie.models import Post, Blog

        hooks = {'post' : self._createPost}

        if not os.path.exists(src + '/_post.html'):
            self.addError('No _post.html found, exiting')
            return self.report

        try:
            dom = parse(src + '/_post.html')
        except xml.dom.DOMException as e:
            self.addError('Error parsing _post.html : ' + e)
            return self.report
            
        if not os.path.exists(output + '/post'):
            os.mkdir(output + '/post')

        posts = Post.objects.all()

        for post in posts:
            #print 'Generate ' + filename
            nodes = dom.getElementsByTagName("*")
            nodes[0] = self.parse(src, hooks, post, dom, nodes[0])
            filename = output + '/post/' 
            filename = filename + post.creation_date.strftime("%Y") + '/' + post.creation_date.strftime("%m") + '/' 
            if not os.path.exists(filename):
                os.makedirs(filename)
            filename = filename + post.title_slug + '.html'
            self.writeIfNotTheSame(filename, nodes[0])
            dom = parse(src + '/_post.html')

        if not self.somethingWrote:
            self.addReport('Nothing changed')

        return self.report

    def createPreview(self, values, dom, root, node):
        now = datetime.datetime.now()

        v = {}
        v['title'] = self.createLinkElem(dom, '/preview.html', values['title'])
        v['author'] = values['author']
        v['date'] = now.strftime("%A, %d %B %Y %H:%m")
        v['post_content'] = ''

        self.simpleTransform(v, dom, root, node)

        content_nodes = root.getElementsByTagName("div")
        post_transform = ('post_content')
        for content_node in content_nodes:
            the_class = content_node.getAttribute('class')
            if not the_class in post_transform:
                continue
            if the_class == 'post_content':
                new_node = dom.createTextNode(values['content'])
                content_node.appendChild(new_node)

        post_nodes = dom.getElementsByTagNameNS(self.URI, "post")
        post_elem = post_nodes[0]
        post_elem.parentNode.removeChild(post_elem)

    def preview(self, src, values):
        from dynastie.models import Blog

        hooks = {'post' : self.createPreview}

        if not os.path.exists(src + '/_post.html'):
            self.addError('No _post.html found, exiting')
            return self.report

        try:
            dom = parse(src + '/_post.html')
        except xml.dom.DOMException as e:
            self.addError('Error parsing _post.html : ' + e)
            return self.report
            
        post_nodes = dom.getElementsByTagNameNS(self.URI, "posts")

        if post_nodes is None:
            self.addError('No tag dyn:posts found')
            return self.report

        nodes = dom.getElementsByTagName("*")
        nodes[0] = self.parse(src, hooks, values, dom, nodes[0])
        writer = StrictUTF8Writer()
        nodes[0].writexml(writer)

        return writer.getvalue().encode('utf-8')
