/*
 * TaskCategoryTagHandler.java
 *
 * Created on 1. März 2007, 10:34
 *
 */

package net.sourceforge.ganttproject.parser;

import java.awt.Color;
import net.sourceforge.ganttproject.task.TaskCategory;
import net.sourceforge.ganttproject.task.TaskCategoryManager;
import net.sourceforge.ganttproject.util.ColorConvertion;
import org.xml.sax.Attributes;

/**
 * SAX handler for processing taskCategory elements
 *
 * @author shofmann <sebastian.hofmann@sourcepark.de>
 */
public class TaskCategoryTagHandler implements TagHandler{
    
    /** Reference to currents project TaskCategoryManager **/
    private TaskCategoryManager taskCategoryManager;
    
    /** 
     * Creates a new instance of TaskCategoryTagHandler 
     * taskCategoryManager currents project TaskCategoryManager
     */
    public TaskCategoryTagHandler(TaskCategoryManager taskCategoryManager) {
        this.taskCategoryManager = taskCategoryManager;
    }

    public void startElement(String namespaceURI, String sName, String qName, 
            Attributes attrs) throws FileFormatException {
        if (qName.equals("taskCategory")) {
            loadCategory(attrs);
        }
    }
    
    private void loadCategory(Attributes attrs) throws FileFormatException{
        
        String idString = attrs.getValue("id");
        String colorString = attrs.getValue("color");
        String descriptionString = attrs.getValue("description");
        
        if(idString == null || colorString == null || descriptionString == null){
            throw new FileFormatException("[TaskCategoryParser] taskCategory " +
                    "needs to have attributes 'id', 'description' and 'color'.");
        }
        
        long id = -1;
        try {
            id = Long.parseLong(idString);
        } catch (Exception e) {
            throw new FileFormatException("[TaskCategoryParser] Attribute " +
                    "id needs to be a long value");
        }
        
        Color color = null;
        try {
            color = ColorConvertion.hexStringToColor(colorString);
        } catch (Exception e) {
            throw new FileFormatException("[TaskCategoryParser] Attribute color" +
                    "needs to be a hexadecimal value, e.g. #ff6600");
        }
        
        TaskCategory category = this.taskCategoryManager.createCategory(id);
        category.setColor(color);
        category.setDescription(descriptionString);
        
        this.taskCategoryManager.addCategory(category);
    }

    public void endElement(String namespaceURI, String sName, String qName) {
        // nothing to do here...
    }
    
}
