#{param name=taskModel/}
#{param name=userTimezone/}
#{param name=bundle/}

<%
import java.text.SimpleDateFormat;
import java.util.Date;
import org.exoplatform.task.util.TaskUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.ArrayUtils;
import org.exoplatform.task.util.ResourceUtil;
import org.exoplatform.task.domain.Priority;
import org.exoplatform.task.util.DateUtil;
import org.exoplatform.commons.utils.HTMLEntityEncoder;

def encoder = HTMLEntityEncoder.getInstance();

def task = taskModel.getTask();
def readOnly = taskModel.isReadOnly();
def breadcumbs = taskModel.getBreadcumbs();
def assignee = taskModel.getAssignee();
def hasAssignee = (assignee != null && assignee.getUsername() != "guest" && assignee.getUsername() != null);
def countCoWorker = taskModel.getNumberCoworkers();
def commentCount = taskModel.getCommentCount();
def comments = taskModel.getComments();
def currentUser = taskModel.getCurrentUser();
def labels = taskModel.getLabels();
def editableClasses = "hoverStatus editableField editable";
def readOnlyClass = "";
if (readOnly) {
    editableClasses = "hoverStatus readOnly";
    readOnlyClass = "readOnly";
}
def locale = bundle != null ? bundle.getLocale() : Locale.getDefault(Locale.Category.FORMAT);

%>
<div class="addTask uiBox ${task.completed ? "task-completed" : ""}" data-taskid="${task.id}">
<div class="uiContentBox">
<div class="clearfix">
<div class="pull-right action-buttons dropdown">
<span class="taskPermalinkContainer" title="&{label.permalink}" data-toggle="tooltip" data-placement="bottom">
<a href="${TaskUtil.buildTaskURL(task)}" data-toggle="popover" data-placement="left"
class="permalink actionIcon taskPermalink" style="position: relative;">
<i class="uiIconPermalink"></i>
            </a>
</span>
        <div class="taskPermalinkPopoverContent" style="display:none">
            <div>
                <i class="uiIconPermalink"></i>
        &{popover.title.linkToShare}
</div>
            <div class="input-field input-xlarge">
                <form method="GET" action="#">
                    <input readonly type="text" name="" value="">
                </form>
</div>
        </div>
<a data-toggle="dropdown" class="dropdown-toggle actionIcon"><i class="uiIconArrowDown"></i></a>
<ul class="dropdown-menu">
<% if (task.status == null || TaskUtil.hasEditPermission(task)) {%>
<li><a class="action-clone-task" href="#"><i class="uiIconCloneNode"></i> &{label.clone}</a></li>
<% }%>
<% if (TaskUtil.hasDeletePermission(task)) {%>
<li><a class="action-delete-task" href="#"><i class="uiIconDelete"></i> &{label.delete}</a></li>
<% }%>
</ul>
        <a class="actionIcon close-right-panel" href="#"><i class="uiIconClose"></i></a>
    </div>

<div class="uiEditableInline clearfix ">
<span class="iconTaskName pull-left"><i
    <% if (!readOnly) {%>
    title="&{tooltip.clickToEdit}" data-toggle="tooltip" data-placement="bottom"
    <% }%>
    class="uiIconFolder"></i></span>
<div class="breadcrumbCont uiEditableInline"
    <% if (!readOnly) {%>
        data-original-title="&{tooltip.clickToEdit}" data-toggle="tooltip" data-placement="bottom"
    <% }%>
>
<ul class=" ${editableClasses} small"
data-name="project" data-type="ParentProject" data-breadcrumb="false" data-value="${task.status == null ? 0 : task.status.project.id}">
        ${breadcumbs}
</ul>
        </div>
</div>
</div>
<div class="tags uiEditableInline clearfix">
<%
def labelHtml = bundle.getString("label.labels");
def labelIds = '';
def labelOptions = '';
if (labels != null && !labels.isEmpty()) {
    labelHtml = "";
    for (def label in labels) {
        def labelName = encoder.encode(label.name);
        labelHtml += '<span class="'+ label.color+' label">' + labelName +'</span>';
        if (labelIds.length() > 0) {
            labelIds += ',';
        }
        labelIds += label.id;
        if (labelOptions.length() > 0) {
            labelOptions += ',';
        }
        labelOptions += '{"id": "'+label.id+'", "text":"' + labelName + '","color":"' + label.color + '"}';
    };
}

%>
<span class="pull-left icon-hash ${labelIds == "" ? "" : "hide"}"><i class="uiIconTag"></i></span>
<div class="${editableClasses} small pull-left"
    <% if (!readOnly) {%>
    data-original-title="&{tooltip.clickToEdit}" rel="tooltip"
    <% }%>
data-name="labels" data-type="selectize" data-inputclass="input-large" data-selectizie-opts='[${labelOptions}]' data-value="${labelIds}">
        ${labelHtml}
</div>
</div>
<div class="taskName uiEditableInline clearfix taskPermalinkContainer">
<div class="title-container clearfix">
<a href="javascript:void(0);"
    <% if (!readOnly) {%>
    data-taskcompleted="${task.completed}" rel="tooltip" data-placement="top"
    <% }%>
    class="pull-left validate-action ${readOnlyClass}" data-original-title="<% if (task.completed) {%> &{message.markAsUnCompleted} <%} else {%> &{message.markAsCompleted} <%}%>">
<%
def uiIconClass = task.completed ? 'uiIconBlue' : 'uiIconLightGray';
%>
<i class="uiIconValidate ${uiIconClass}"></i>
      </a>
<span class="projectName ${editableClasses} small "
    <% if (!readOnly) {%>
    data-original-title="&{tooltip.clickToEdit}" rel="tooltip" data-placement="bottom"
    <% }%>
data-name="title" data-type="text" data-emptytext="&{label.untitledTask}">
        ${encoder.encode(task.title)}
</span>
    </div>
</div>

<%
 SimpleDateFormat dueDateFormat = new SimpleDateFormat('dd MMM yyyy',locale);
 dueDateFormat.setTimeZone(userTimezone);
%>
<div class="inforBar1 clearfix">
    <div class="pull-left">
        <div class="uiEditableInline">
            <i class="uiIconClock"></i>
<span class="${editableClasses} small dueDateField"
    <% if (!readOnly) {%>
    data-original-title="&{tooltip.clickToEdit}" rel="tooltip" data-placement="top" data-name="duedate"
    <% }%>
data-type="calendar"
data-value="${task.dueDate != null ? task.dueDate.format('yyyy-MM-dd', userTimezone) : ''}"
data-format="yyyy-MM-dd" data-viewformat="dd M yyyy">
    <%
        if (task.dueDate != null) {
            print dueDateFormat.format(task.dueDate);
        } else if (readOnly) {
            print "Due date";
        }
    %>
</span>
        </div>
</div>
    <div class="pull-left">
        <div class="uiEditableInline inactive">
            <span>
                <span class="unassigned ${!hasAssignee ? "" : "hide"}"><i class="uiIconUser"></i></span>
                <a class="avatarMini pull-left assigned ${!hasAssignee ? "hide" : ""}" href="#">
                    <img alt="avatar" src="${hasAssignee ? assignee.avatar : ""}">
                </a>
<a
    <%
    def editAssignee = "";
    if (!readOnly) {
        editAssignee = "editAssignee";
    %>
    title="&{tooltip.clickToEdit}" data-toggle="tooltip" data-placement="bottom"
    <% }%>
    class="hoverStatus small
    <% if (!readOnly) {%>
    editableField
    <% } else {%>
    readOnly
    <% }%>
    ${editAssignee} ${hasAssignee && countCoWorker == 0 && assignee.deleted ? "muted" : ""}">
<% if (countCoWorker > 0) {%>
    +${countCoWorker} ${bundle.getString(countCoWorker > 1 ? "label.coworkers" : "label.coworker").toLowerCase()}
    <%} else if (hasAssignee) {%>
    ${encoder.encode(assignee.displayName)} <% if (!assignee.enable) {%> <span class = "muted"><i>(&{label.inactive})</i></span> <%}%>
    <%} else {%>
    &{label.unassigned}
    <%}%>
</a>
            </span>
<div class="uiBox assignmentPopup" style="display: none; position: absolute; left: auto; right: 0; top: 30px; width: 300px; z-index: 9">
<div class="uiContentBox">
<div class="contBlock">
<div class="mgB10 mgT5">&{label.assignTo}:</div>
                        <div class="inputUser">
                            <input type = "text" name="assignee" value="${hasAssignee ? encoder.encode(task.assignee) : ""}"/>
<a href="javascript:void(0);" data-action="assign" data-value="${currentUser.username}">&{label.assignToMe}</a>
                        </div>
</div>
                    <div class="contBlock tags">
                        <%
                            def coWorkers = "";
                            if(task.coworker != null && task.coworker.size() > 0) {
                                coWorkers = task.coworker.join(',');
                            }
                        %>
                        <div class="mgB10 mgT5">&{label.coworkers}:</div>
<input type="text" name="coworker" value="${encoder.encode(coWorkers)}"/>
<a href="javascript:void(0);" data-action="add-coworker" data-value="${currentUser.username}">&{label.addMeAsCoworker}</a>
                    </div>
</div>
            </div>
</div>

    </div>
<div class="pull-left">
<div class="toDo">
<div class="uiEditableInline">
<% if (task.status != null) {
    def currentLabel = ResourceUtil.resolveStatus(bundle, task.status.name);
    %>
    <i class="uiIconTime"></i>
                    <span  class="${readOnlyClass} hoverStatus editableField editable small" href="javascript:void(0)"
                       <% if (!readOnly) {%>
                       data-original-title="&{tooltip.clickToEdit}" rel="tooltip"
                       <% }%>
                       data-name="status" data-source="@{StatusController.getAllStatus(projectId=task.status.project.id)}"
                       data-inputclass="selectboxMini" data-type="select"
                       data-title="Select status" data-val="${task.status != null ?  task.status.id: '0'}" 
                       data-label="${currentLabel}"></span>
    <%}  %>
</div>
        </div>
</div>
</div>
<div class="taskDescription">
<div data-type="ckeditor" data-name="description" class="${editableClasses}"
    <% if (!readOnly) {%>
    data-original-title="&{tooltip.clickToEdit}" rel="tooltip"
    <% }%>
>
        ${task.description == null ? "" : task.description}
</div>
</div>
<div class="inforBar2 clearfix">
<div class="pull-left">
<%
def startDate = task.getStartDate();
def endDate = task.getEndDate();

def workplan = bundle.getString("label.noWorkPlan");
def duration = 0;
if (startDate != null) {
    def start = DateUtil.newCalendarInstance(userTimezone);
    start.setTime(task.getStartDate());
    def end = DateUtil.newCalendarInstance(userTimezone);
    end.setTime(task.getEndDate());
    workplan = TaskUtil.getWorkPlan(start, end, bundle);
    duration = endDate.getTime() - startDate.getTime();
}

def hasPlan = true;
if(startDate == null) {
    hasPlan = false;
    def startTmp = DateUtil.newCalendarInstance(userTimezone);
    startTmp.set(Calendar.MINUTE, 0);
    startDate = startTmp.getTime();
    duration = 30 * 60 * 1000;
}
def endTmp = DateUtil.newCalendarInstance(userTimezone);
endTmp.setTimeInMillis(startDate.getTime() + duration);
endDate = endTmp.getTime();

def df = new SimpleDateFormat("YYYY-MM-dd-HH-mm");
df.setTimeZone(userTimezone);

def dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setTimeZone(userTimezone);

def timeFormat = new SimpleDateFormat("HH:mm");
timeFormat.setTimeZone(userTimezone);

int halfHour = 30 * 60 * 1000;
def isAllday = false;
if (duration > halfHour * 47 && duration <= halfHour * 48) {
    isAllday = true;
}
%>
<div class="uiEditableInline clearfix fieldWorkPlan inactive ${readOnlyClass}"
data-startdate="<%=df.format(startDate)%>" data-duration="${duration}">
<% if (!readOnly) {%>
<div class="pull-right">
            <span title="&{label.remove}" data-placement="bottom" data-toggle="tooltip"  class="actionIcon inline-hide removeWorkPlan ${hasPlan ? "" : "hide"}"><i class="uiIcon uiIconTrashMini"></i></span>
</div>
<% }%>
            <div class="date-work-plan">
            <%
            	def inCal = task.isCalendarIntegrated();
            	def iconIntegCal = inCal ? "uiIconPLFBlue" : "";
            	def title = inCal ? bundle.getString("tooltip.removeFromCalendar") : bundle.getString("tooltip.addToCalendar");
            %>
            <i class="uiIconPLFCalendar pull-left ${iconIntegCal} ${readOnlyClass}"
                <% if (!readOnly) {%>
                rel="tooltip" title="${title}"
                <% }%>
                data-integrated="${inCal}" data-title-add="&{tooltip.addToCalendar}" data-title-remove="&{tooltip.removeFromCalendar}"></i>
<span
    <% if (!readOnly) {%>
    data-original-title="&{tooltip.clickToEdit}" rel="tooltip" data-placement="bottom"
    <% }%>
    class="hoverStatus hoverStatusBlock small ${readOnly ? "readOnly" : "editableField"}">${workplan}</span></div>
<div class = "rangeCalendar" style = "display: none">
<div class="rangeCalendar-container">
<div class="row-fluid">
<div class="span6">
    <strong>&{label.from}</strong>
    <div class="uiCalendarComponent" id="BlockCalendar1">
        <input name="fromDate" type="hidden" value="${hasPlan ? dateFormat.format(startDate) : ""}" />
    </div>
</div>
<div class="span6">
    <strong>&{label.to}</strong>
    <div class="uiCalendarComponent" id="BlockCalendar2">
        <input name="toDate" type="hidden" value="${hasPlan ? dateFormat.format(endDate) : ""}" />
    </div>
</div>
</div>
                    
<!-- /.clearfix -->
                    <div class="row-fluid choose-time ${isAllday} ${isAllday || !hasPlan ? "all-day" : ""}">
                        <div class="span5 center timeSelector">
                            <div class="form-dropdown">
                                <input data-toggle="dropdown" class="input-size-mini" type="text" name="fromTime" maxlength="5" value="${isAllday ? "00:00" : timeFormat.format(startDate)}">
                                <ul class="dropdown-menu">
                                    <%for(int i = 0; i <= 23; i++) {
                                        def hour = i < 10 ? "0" + i : i;
                                    %>
                                        <li><a href="javascript:void(0)" data-time="${hour}:00">${hour}:00</a></li>
                                        <li><a href="javascript:void(0)" data-time="${hour}:30">${hour}:30</a></li>
                                    <%}%>
                                </ul>
</div>
                        </div>
<div class="span2 center">
<label class="uiCheckbox">
<input type="checkbox" name="allday" class="checkbox" ${isAllday || !hasPlan ? 'checked="true"' : ''}>
<span>&{label.allday}</span>
                            </label>
</div>
                        <div class="span5 center timeSelector">
                            <div class="form-dropdown">
                                <input data-toggle="dropdown" class="input-size-mini" type="text" name="toTime" maxlength="5" value="${isAllday ? '23:59' : timeFormat.format(endDate)}">
                                <ul class="dropdown-menu">
                                    <%for(int i = 0; i <= 23; i++) {
                                        def hour = i < 10 ? "0" + i : i;
                                    %>
                                        <li><a href="javascript:void(0)" data-time="${hour}:00">${hour}:00</a></li>
                                        <li><a href="javascript:void(0)" data-time="${hour}:30">${hour}:30</a></li>
                                    <%}%>
                                </ul>
</div>
                        </div>
</div>
                    <div class="row-fluid center error errorMessage"></div>
</div>
            </div>
</div>
    </div>
<div id="due-warning" style="display: none;" class="alert alert-warning dueAlertWarning"><i class="uiIconWarning"></i>&{message.dueDateBeforeEndDate}</div>
<div class="priority pull-left">
<div class="uiEditableInline">
<i  class="uiIconColorPriority${task.priority != null ?  task.priority : Priority.NONE}"></i>
            <%
                Priority[] ps = Priority.values();
                String[] arrays = new String[ps.length];
                for (int i = ps.length - 1; i >= 0; i--) {
                    String name = ps[i].name();
                    arrays[ps.length - 1 - i] = '{"value": "'+name+'", "text": "'+bundle.getString('label.priority.' + name.toLowerCase())+'"}';
                }

                def priorities = "[" + StringUtils.join(arrays, ",") + "]";
            %>
            <span class="task-priority ${readOnlyClass} hoverStatus editableField editable small"
                  <% if (!readOnly) {%>
                  data-original-title="&{tooltip.clickToEdit}" rel="tooltip"
                  <% }%>
                  data-inputclass="selectboxMini"
               data-name="priority" data-source='${priorities}' data-type="select" data-emptytext="&{label.noPriority}"
               data-value="${task.priority != null ?  task.priority : Priority.NONE}"></span>
</div>
    </div>

</div>
<div id="tab-action" class="uiTabPane uiTabNormal">
    <ul id="myTab" class="nav nav-tabs">
        <li class="active">
            <a href="#tab-comments" data-toggle="tab">&{label.comments}</a>
</li>
        <li class="taskTabs">
            <a href="#tab-changes" data-toggle="tab">&{label.changes}</a>
</li>
    </ul>
<div id="myTabContent" class="tab-content">
<div id="tab-comments" class="tab-pane fade in active ">
#{include path=taskComments.gtmpl /}
</div>
        <div id="tab-changes" class="tab-pane fade taskLogs">

        </div>
</div>
</div>
</div>
</div>
    <script type="text/javascript">
            require(['taskDetailView'], function(detail) {
                detail.init();
            })
    </script>
