# -*- coding: utf-8 -*-

# Copyright (c) 2005 - 2006 Detlev Offenbach <detlev@die-offenbachs.de>
#

"""
Module implementing the handler class for reading an XML tasks file.
"""

import os
import time

from qt import qApp

from Config import tasksFileFormatVersion
from XMLHandlerBase import XMLHandlerBase

class TasksHandler(XMLHandlerBase):
    """
    Class implementing a sax handler to read an XML tasks file.
    """
    def __init__(self, forProject=0, taskViewer=None):
        """
        Constructor
        
        @param forProject flag indicating project related mode (boolean)
        @param taskViewer reference to the task viewer object
        """
        XMLHandlerBase.__init__(self)
        
        self.startDocumentSpecific = self.startDocumentTasks
        
        self.elements.update({
            'Tasks' : (self.startTasks, self.defaultEndElement),
            'Description' : (self.defaultStartElement, self.endDescription),
            'Created' : (self.defaultStartElement, self.endCreated),
            'Dir' : (self.defaultStartElement, self.endDir),
            'Name' : (self.defaultStartElement, self.endName),
            'Filename' : (self.startFilename, self.endFilename),
            'Linenumber' : (self.defaultStartElement, self.endLinenumber),
            'Task' : (self.startTask, self.endTask),
        })
    
        self.forProject = forProject
        if taskViewer:
            self.taskViewer = taskViewer
        else:
            self.taskViewer = qApp.mainWidget().getTaskViewer()
        
    def startDocumentTasks(self):
        """
        Handler called, when the document parsing is started.
        """
        self.pathStack = []
        
    ###################################################
    ## below follow the individual handler functions
    ###################################################
    
    def startTask(self, attrs):
        """
        Handler method for the "Task" start tag.
        
        @param attrs list of tag attributes
        """
        self.task = ["",                # description
                     1,                 # priority
                     0,                 # completed
                     0,                 # created
                     "",                # filename
                     0,                 # linenumber
                     0,                 # bugfix task flag
                    ]
        self.task[1] = int(attrs.get("priority", "1"))
        self.task[2] = int(attrs.get("completed", "0"))
        self.task[6] = int(attrs.get("bugfix", "0"))
    
    def endTask(self):
        """
        Handler method for the "Task" end tag.
        """
        self.taskViewer.addTask(self.task[0], priority = self.task[1],
            filename = self.task[4], lineno = self.task[5], completed = self.task[2],
            _time = self.task[3], isProjectTask = self.forProject,
            isBugfixTask = self.task[6])
        
    def endDescription(self):
        """
        Handler method for the "Description" end tag.
        """
        self.task[0] = self.utf8_to_code(self.buffer)
        
    def endCreated(self):
        """
        Handler method for the "Created" end tag.
        """
        self.buffer = self.utf8_to_code(self.buffer)
        self.task[3] = time.mktime(time.strptime(self.buffer, "%Y-%m-%d, %H:%M:%S"))
    
    def endDir(self):
        """
        Handler method for the "Dir" end tag.
        """
        self.buffer = self.utf8_to_code(self.buffer)
        self.pathStack.append(self.buffer)
        
    def endName(self):
        """
        Handler method for the "Name" end tag.
        """
        self.buffer = self.utf8_to_code(self.buffer)
        self.pathStack.append(self.buffer)
        
    def endLinenumber(self):
        """
        Handler method for the "Linenumber" end tag.
        """
        try:
            self.task[5] = int(self.buffer)
        except ValueError:
            pass
    
    def startFilename(self, attrs):
        """
        Handler method for the "Filename" start tag.
        
        @param attrs list of tag attributes
        """
        self.pathStack = []
        
    def endFilename(self):
        """
        Handler method for the "Filename" end tag.
        """
        self.task[4] = self.buildPath()
        
    def buildPath(self):
        """
        Private method to assemble a path.
        
        @return The ready assembled path. (string)
        """
        path = ""
        if self.pathStack and not self.pathStack[0]:
            self.pathStack[0] = os.sep
        for p in self.pathStack:
            path = os.path.join(path, p)
        return path
        
    def startTasks(self, attrs):
        """
        Handler method for the "Tasks" start tag.
        
        @param attrs list of tag attributes
        """
        self.version = attrs.get('version', tasksFileFormatVersion)
        
    def getVersion(self):
        """
        Public method to retrieve the version of the tasks file.
        
        @return String containing the version number.
        """
        return self.version
