package com.quantumdigital.ithelp.timeanalyzer

import com.jdbernard.timeanalyzer.Category
import com.jdbernard.timeanalyzer.Entry
import com.jdbernard.timeanalyzer.Event

public class ITHelpCategory extends Category {

    private def ithelpPattern = ~/^ITHelp:\s*(.*)$/
    private def ticketPattern = ~/^ITHelp:.*#(\d+).*/

    public boolean matchesEvent(Event e) {
        return (e.description ==~ ithelpPattern)
    }

    public Entry addEvent(Event e) {
        
        Entry entry

        // try to add to an existing category
        entry = addToSubcategory(e)

        // no existing category matches
        if (!entry) {

            // see if it is a new ticket entry
            def ticketMatch = e.description =~ ticketPattern

            // if is a new ticket
            if(ticketMatch) {
                // parse the ticket number
                int ticketId = ticketMatch[0][1] as int

                // create the category
                TicketCategory category = new TicketCategory(ticketId)

                // add the category to our list
                categories << category

                // add the event to the category
                entry = category.addEvent(e)
            }
            
            // not a new ticket, use the general logic for adding
            else {
                
                // add a general entry to this category
                entry = super.addEvent(e)

                // adjust the description (remove the ITHelp tag)
                def m = entry.description =~ ithelpPattern
                entry.description = m[0][1]
            }
        }

        return entry
    }
}
