<%@ taglib uri="webwork" prefix="webwork" %>
<%@ taglib uri="sitemesh-page" prefix="page" %>

<%@ page import="com.atlassian.core.ofbiz.CoreFactory,
                 com.atlassian.jira.ComponentManager,
                 com.atlassian.jira.ManagerFactory,
                 com.atlassian.jira.issue.Issue,
                 com.atlassian.jira.issue.history.ChangeItemBean,
                 com.atlassian.jira.issue.history.ChangeLogUtils,
                 com.atlassian.jira.issue.worklog.Worklog,
                 com.atlassian.jira.issue.worklog.WorklogManager,
                 com.opensymphony.user.User,
                 com.opensymphony.user.UserManager,
                 org.ofbiz.core.entity.GenericValue,
                 org.ofbiz.core.util.UtilMisc,
                 javax.servlet.http.HttpServletRequest,
                 java.util.ArrayList,
                 java.util.List,
                 java.util.Locale"%>
<%@ page import="java.text.SimpleDateFormat"%>
<%@ page import="java.sql.Timestamp"%>
<%!
    GenericValue getIssue(String key) throws Exception
    {
        GenericValue issue = ManagerFactory.getIssueManager().getIssue(key);
        if (issue == null) throw new RuntimeException("No issue with key '" + key + "'");
        return issue;
    }

    Issue getIssueObject(String key) throws Exception
    {
        Issue issue = ManagerFactory.getIssueManager().getIssueObject(key);
        if (issue == null) throw new RuntimeException("No issue with key '" + key + "'");
        return issue;
    }

    List getWorklogs(String key, HttpServletRequest request) throws Exception
    {
        User user = UserManager.getInstance().getUser(request.getRemoteUser());
        return ((WorklogManager) ComponentManager.getComponentInstanceOfType(WorklogManager.class)).getWorklogsForUser(getIssueObject(key), user);
    }

    Worklog getWorklog(String key, String action, HttpServletRequest request) throws Exception
    {
        List worklogs = getWorklogs(key, request);
        for (int i = 0; i < worklogs.size(); i++)
        {
            Worklog worklog = (Worklog) worklogs.get(i);
            if (new Long(action).equals(worklog.getId()))
            {
                return worklog;
            }
        }
        throw new RuntimeException("No worklog on issue " + key + " with id " + action);
    }

    void updateWorklog(String key, String actionStr, String periodMins, String dateCreated, String comment, HttpServletRequest request) throws Exception
    {
        GenericValue issue = getIssue(key);
        User user = UserManager.getInstance().getUser(request.getRemoteUser());
        Long action = new Long(actionStr);
        long period = Long.parseLong(periodMins) * 60;
        List actions = CoreFactory.getGenericDelegator().findByAnd("Action", UtilMisc.toMap("id", action));
        if (actions.size() == 0) throw new RuntimeException("Could not find action with id " + action);
        GenericValue worklogGV = (GenericValue) actions.get(0);

        // Update time
        Long oldPeriod = worklogGV.getLong("numvalue");
        worklogGV.set("numvalue", new Long(period));
        worklogGV.store();

        List changeItems = new ArrayList();

        long diff = period - oldPeriod.longValue();
        if (diff != 0) {
            adjustIssueField(issue, "timespent", diff, changeItems);
            adjustIssueField(issue, "timeestimate", -diff, changeItems);
            issue.store();
        }

        // Update date
        Timestamp oldDate = worklogGV.getTimestamp("created");
        Timestamp newDate = new Timestamp(new SimpleDateFormat().parse(dateCreated).getTime());
        if (!oldDate.equals(newDate)) {
            System.out.println("Updating date from " +oldDate+" to "+ newDate);
            worklogGV.set("created", newDate);
            worklogGV.store();
            changeItems.add(new ChangeItemBean(ChangeItemBean.STATIC_FIELD, "worklog.date", ""+oldDate, ""+newDate));
        }

        // Update comment
        String oldComment = worklogGV.getString("body");
        if (!comment.equals(oldComment)) {
            System.out.println("Comment: from: "+oldComment+" to: "+comment);
            worklogGV.set("body", comment);
            worklogGV.store();
            changeItems.add(new ChangeItemBean(ChangeItemBean.STATIC_FIELD, "worklog.comment", ""+oldComment, ""+comment));
        }

        ManagerFactory.getCacheManager().flushAll();

        ChangeLogUtils.createChangeGroup(user, issue, issue, changeItems, true);
    }

    void adjustIssueField(GenericValue issue, String field, long diff, List changeItems)
    {
        Long origTime = issue.getLong(field);
        System.out.println("Field " + field + ": Adding " + diff + " to " + origTime);
        Long timeSpent = new Long(origTime.longValue() + diff);
        issue.set(field, timeSpent);
        changeItems.add(new ChangeItemBean(ChangeItemBean.STATIC_FIELD, field, "" + origTime, "" + timeSpent));
    }

    public String getPrettyDuration(Long duration, Locale locale)
    {
        return ComponentManager.getInstance().getJiraDurationUtils().getFormattedDuration(duration, locale);
    }
%>
<html>
<body>
<h2><webwork:text name="'admin.editworklog.worklog.editor'"/></h2>
<p><webwork:text name="'admin.editworklog.page.description'">
    <webwork:param name="'value0'"><a href="http://jira.atlassian.com/browse/JRA-2411"></webwork:param>
    <webwork:param name="'value1'"></a></webwork:param>
</webwork:text></p>
<% try { %>
<%
    String key = request.getParameter("key");
    String action = request.getParameter("action");
    String period = request.getParameter("period");
    String dateCreated = request.getParameter("datecreated");
    String comment = request.getParameter("comment");
	boolean choseWorklog = (action != null && period == null);
	boolean updateWorklog = (key != null && action != null && (period != null || dateCreated != null || comment != null));
    if (updateWorklog) updateWorklog(key, action, period, dateCreated, comment, request);
%>

<form>
<webwork:text name="'admin.editworklog.issue.key'"/>: <input name="key" value="<%=(key == null ? "" : key)%>" />
<% if (key != null) { %>
<h4><webwork:text name="'admin.editworklog.work.logs.for'">
    <webwork:param name="'value0'"><a href="<%=request.getContextPath()%>/browse/<%=key%>"><%=key%></a></webwork:param>
</webwork:text></h4>

<br><table border="1" cellpadding="5">
<tr><th><webwork:text name="'admin.editworklog.user'"/></th><th><webwork:text name="'admin.editworklog.time.spent'"/></th><th><webwork:text name="'issue.field.date.created'"/></th><th><webwork:text name="'admin.editworklog.comment'"/></th></tr>
<%
    List worklogs = getWorklogs(key, request);
    for (int i = 0; i < worklogs.size(); i++)
    {
        Worklog worklog = (Worklog) worklogs.get(i);
        out.println("<tr"+
                (updateWorklog && worklog.getId().longValue() == Long.parseLong(action) ? " bgcolor='#ffffee'>": ">") +
                "<td>"+worklog.getAuthorFullName()+"</td>"
                +"<td>"+getPrettyDuration(worklog.getTimeSpent(), request.getLocale())+"</td>"+
                "<td>"+(worklog != null ? new SimpleDateFormat().format(worklog.getTimePerformed()) : "")+"</td>" +
                "<td>" + (worklog != null ? worklog.getComment() : "") + "</td>"+
                "<td><a href=editworklog.jsp?key="+key+"&action="+worklog.getId()+">[edit]</a>"+
                "</td></tr>");
    }
    %>
</table>
<p>
<% if (choseWorklog) { %>

<page:applyDecorator name="jiraform">
    <page:param name="title">Update Worklog</page:param>
    <page:param name="action"><webwork:text name="'common.forms.update'"/></page:param>
    <page:param name="description"></page:param>
        <input name="key" type="hidden" value="<%= key %>" />
        <input name="action" type="hidden" value="<%= action %>" />
        <tr><td><webwork:text name="'admin.editworklog.enter.new.time.period'"/>:</td> <td><input size="10" name="period" value="<%=getWorklog(key, action, request).getTimeSpent().longValue()/60%>" /></td></tr>
        <tr><td><webwork:text name="'issue.field.date.created'"/>:</td> <td><input name="datecreated" value="<%=new SimpleDateFormat().format(getWorklog(key, action, request).getTimePerformed())%>"/></td></tr>
        <tr><td>Comment: </td><td><textarea rows="15" cols="60" wrap="virtual" name="comment"><%=getWorklog(key, action, request).getComment() %></textarea></td></tr>
        <tr><td colspan="2"><input type="submit" value="<webwork:text name="'common.forms.update'"/>"></td></tr>
</page:applyDecorator>
    <% }
    } %>
</p>
</form>

<% } catch (Throwable t) {
t.printStackTrace();
%>
<h3><font color="red"><webwork:text name="'common.words.error'"/>: <%=t%> </font></h3>
<p>
<% } %>
</body>
</html>
