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

class Tag(Index):

    cur_page = 0
    nb_pages = 0
    cur_post = 0
    posts_per_page = 0
    filename = 'index'
    dirname = ''
    cur_tag = None

    def createTag(self, posts, dom, root, node):
        if node.hasAttribute('name'):
            self.replaceByText(dom, root, node, self.cur_tag.name)
        if node.hasAttribute('description'):
            self.replaceByText(dom, root, node, self.cur_tag.description)
        return None

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

        self.hooks = {'posts' : self.createPosts,
                      'navigation' : self.createNavigation,
                      'tag' : self.createTag,
                      'tags' : self.createTags,
                      'replace' : self.createReplace}

        self.blog = blog

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

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

        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 = 5
        else:
            self.addError('No tag dyn:posts found')

        tags = Tag.objects.all()

        for tag in tags:
            self.cur_tag = tag
            filename = self.filename + '.html'
            posts = Post.objects.filter(tags__in=[tag.id], published=True).order_by('-creation_date')

            self.nb_pages = 0
            self.cur_page = 0
            self.cur_post = 0

            self.dirname = '/tag/' + tag.name_slug

            if posts.count() > self.posts_per_page:
                self.nb_pages = self.computeNbPages(posts.count(), self.posts_per_page)

            if not os.path.exists(output + self.dirname):
                os.mkdir(output + self.dirname)
                

            while self.cur_page <= self.nb_pages:
                #print 'Generate ' + filename
                nodes = dom.getElementsByTagName("*")
                nodes[0] = self.parse(src, self.hooks, posts, dom, nodes[0])
                self.writeIfNotTheSame(output + self.dirname + '/' + filename, nodes[0])
                self.cur_page = self.cur_page + 1
                filename = self.filename + str(self.cur_page) + '.html'
                dom = parse(src + '/_tag.html')

            while os.path.exists(filename):
                self.addReport('Removing unused ' + filename)
                os.unlink(filename)
                filename = filename + '.gz'
                if os.path.exists(filename):
                    self.addReport('Removing unused ' + filename)
                    os.unlink(filename)
                self.cur_page = self.cur_page + 1
                filename = output + self.dirname + '/' + self.filename + str(self.cur_page) + '.html'

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

        return self.report

