package com.atlassian.confluence.extra.dynamictasklist.model;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Collections;

/**
 * Defines a very simple task list model.
 * <p/>
 * Tasks are text strings, one per line.
 */
public class TaskList
{
    private String name;
    private List tasks;

    public TaskList()
    {
    }

    public TaskList(String name)
    {
        this.name = name;
        tasks = Collections.synchronizedList(new ArrayList());
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public List getTasks()
    {
        return tasks;
    }

    public void setTasks(List tasks)
    {
        this.tasks = tasks;
    }

    public int getTotalTasks()
    {
        return tasks.size();
    }

    public int getCompleteTasks()
    {
        int complete = 0;

        for (Iterator iterator = getTasks().iterator(); iterator.hasNext();)
        {
            Task task = (Task) iterator.next();
            if (task.isCompleted())
            {
                complete++;
            }
        }
        return complete;
    }

    public int getPercentComplete()
    {
        int complete = getCompleteTasks();
        return (int) (100f * ((float) complete / (float) tasks.size()));
    }

    public void addTask(String task)
    {
        tasks.add(new Task(task));
    }

    public Task getTask(String taskName)
    {
        for (Iterator iterator = tasks.iterator(); iterator.hasNext();)
        {
            Task task = (Task) iterator.next();
            if (task.getName().equals(taskName))
            {
                return task;
            }
        }

        return null;
    }

    public void removeTask(String task)
    {
        tasks.remove(getTask(task));
    }

    public void setTaskIndex(String taskName, int idx)
    {
        Task task = getTask(taskName);
        if (task != null)
        {
            try
            {
                tasks.remove(task);
                tasks.add(idx, task);
            }
            catch (IndexOutOfBoundsException e)
            {
                tasks.remove(task);
                tasks.add(task);
            }
        }
    }

    public String getNiceName()
    {
        return name.replaceAll("_", " ");
    }
}