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 generate(self, blog, src, output):
        from dynastie.models import Post, Blog

        self.hooks['archive'] = self.createArchive

        dom = self.parseTemplate(blog, src, output, 'archive', 'archive')
        if dom is None: return self.report

        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.nb_pages = 0
                    self.cur_page = 0
                    self.cur_post = 0

                    self.dirname = '/archive/' + str(self.cur_year)
                
                    self.generatePages(dom, my_post, src, output, 'archive', 'archive')
                    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(posts[i])
                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 not self.somethingWrote:
            self.addReport('Nothing changed')

        return self.report

