# -*- coding: utf-8 -*-
"""
  Copyright 2012-2013 Grégory Soutadé

  This file is part of Dynastie.

  Dynastie is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  Dynastie is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with Dynastie.  If not, see <http://www.gnu.org/licenses/>.
"""
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')