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

    cur_page = 0
    nb_pages = 0
    cur_post = 0
    posts_per_page = 0
    filename = 'index'
    dirname = ''
    cur_year = 0

    def createArchive(self, posts, dom, root, node):
        if node.hasAttribute('year'):
            self.replaceByText(dom, root, node, str(self.cur_year))

        return None

    def createArchives(self, src, output, dom, hooks, posts):
        filename = self.filename + '.html'
        self.nb_pages = 0
        self.cur_page = 0
        self.cur_post = 0

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

        self.dirname = '/archive/' + str(self.cur_year)
                
        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, 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 + '/_archive.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'

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

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

        self.blog = blog

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

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

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

        posts = Post.objects.filter(published=True, front_page=True).order_by('creation_date')

        if posts.count() != 0:
            self.cur_year = int(posts[0].creation_date.year)

        my_post = []
        now = datetime.now()
        nb_post = len(posts)
        for i in range(0, nb_post):
            if self.cur_year == now.year:
                break

            if i < nb_post-1:
                if posts[i].creation_date.year != posts[i+1].creation_date.year:
                    dom = parse(src + '/_archive.html')
                    my_post.reverse()
                    self.createArchives(src, output, dom, self.hooks, my_post)
                    self.cur_year = int(posts[i+1].creation_date.year)
                    #print 'New year ' + str(self.cur_year)
                    my_post = []
                    if self.cur_year == int(now.year):
                        break
                else:
                    my_post.append(posts[i])
            else:
                # Last post
                my_post.append(post)
                if nb_post != 1 and posts[i].creation_date.year != posts[i-1].creation_date.year:
                    self.cur_year = int(posts[i].creation_date.year)

        if len(my_post) != 0:
            self.createArchives(src, output, dom, self.hooks, my_post)

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

        return self.report

