import os
from datetime import datetime
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 Search(Index):

    def createNoResultFound(self, posts, dom, root, node):
        posts_elem = self.createElement(dom, 'posts', '<b>No result found</b>')
        root.replaceChild(posts_elem, node)
        return posts_elem

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

        self.blog = blog

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

        try:
            dom = parse(src + '/_search.html')
        except xml.dom.DOMException as e:
            self.addError('Error parsing _search.html : ' + e)
            return self.report
            
        post_nodes = dom.getElementsByTagNameNS(self.URI, "posts")
        if not post_nodes is None:
            if post_nodes[0].hasAttribute("limit"):
                self.posts_per_page = int(post_nodes[0].getAttribute("limit"))
            else:
                self.posts_per_page = 25
        else:
            self.addError('No tag dyn:posts found')

        if len(post_list) == 0:
            self.hooks['posts'] = self.createNoResultFound

        posts = []
        for post_id in post_list:
            try:
                post = Post.objects.get(pk=post_id)
            except:
                continue
            if not post is None:
                posts.append(post)

        nodes = dom.getElementsByTagName("*")
        nodes[0] = self.parse(src, self.hooks, posts, dom, nodes[0])

        writer = StrictUTF8Writer()
        nodes[0].writexml(writer)
        return writer.getvalue().encode('utf-8')

