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 Category(Index):

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

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

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

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

        self.blog = blog

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

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

        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')

        categories = Category.objects.all()

        for category in categories:
            self.cur_category = category
            filename = self.filename + '.html'
            posts = Post.objects.filter(category__exact=category, published=True).order_by('-creation_date')

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

            self.dirname = '/category/' + category.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 + '/_category.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

