<% the_current_user = current_user %>
<% last_complete_build = project.last_complete_build %>

<div id="project_<%= project.identifier %>" class="project build_<%= project.last_complete_build_status %> row">

	<div class="col-sm-12 col-md-6">

      <div class="lamp" style="width:50px; float:left; position:absolute;">
        <% if project.is_building? %>
            <div id='lava'>
              <img src="/images/buildwise/lava_orange_animation.gif" width="32" height="43" style="margin-left: 0px;"/>
            </div>
        <% else %>
            <% if last_complete_build.nil? %>
                <div id='lava'><img src="/images/buildwise/lava_white.png" width="32" height="43"/></div>
            <% elsif last_complete_build.successful %>
                <div id='lava'><img src="/images/buildwise/lava_green.png" width="32" height="43"/></div>
            <% else %>
                <div id='lava'><img src="/images/buildwise/lava_red.png" width="32" height="43"/></div>
            <% end %>
        <% end %>
      </td>
		</div>
		
  <table class="project_pane" style=" margin-left: 55px;">
    <tr>
      <td class="project_summary" width="400" valign="top" style="padding-top: 8px;">
        <div>
		      <span class="project_name">
		        <%= link_to project.name || project.identifier, "/projects/#{project.id}/edit", "data-toggle"=>"tooltip", "data-placement"=>"top", "title"=>"View/Change config" %>
		      </span>
					<label style="margin-bottom: 5px; display: inline;"><a href="/projects/<%= project.identifier%>/report" data-toggle='tooltip' data-placement='top' title='<%= I18n.t(:project_chart)%>'>
            <i style="font-size: 1.3em;" class="fa fa-line-chart <% if last_complete_build.nil? %>gray<% elsif last_complete_build.successful %>green<% else %>red<% end %>" aria-hidden="true" ></i>
						</a>
          </label>
        </div>

        <div class="recent_builds" style="margin-top: 6px; font-size: 14px;">

					<div class="project-builds-chart-container" id="project-chart-<%= project.id %>" ></div>
					<div class="recent-2-builds" style="">
								
			          <% recent_builds = project.last_two_builds %>
			          <% if !recent_builds.first %>
			   		    	<span class="lead"><span class="build_status"><%= I18n.t(:never_built) %></span>
			          <% end %>
   
				        <% unless recent_builds.empty? %>
			              <div class="builds_list">
			                <% recent_builds.each_with_index do |build, idx| %>
			                    <% if build.status == "complete" %>
			                        <div class="build_list_<%= build.status %>_<%= build.successful %> project_build_history_item <% unless idx == 0 %>project_build_history_item_past <% end %>" ><span data-localtime-format><%= build.start_time.iso8601 %></span>
																<br/>
			                          <a href="/builds/<%= build.id %>" <% if idx == 0%>style='font-weight: 550;'<% end %>><%= build.label.rjust(3, ' ') rescue build.id %>: <%= build.successful ? "OK" : "Failed" %></a> 
														
																	<% if build.duration %>														
																		<i class="fa fa-clock-o" aria-hidden="true"></i>
																		<%= build.pretty_duration %>
																	<% end %>
														
			                        </div>
			                    <% elsif build.status == "building" %>
			                        <div class="build_list_<%= build.status %> project_build_history_item  <% unless idx == 0 %>project_build_history_item_past <% end %>">
									  <span data-localtime-format><%= build.start_time.iso8601 %></span>
										<br/>
			                          <b><a href="/builds/<%= build.id %>"><%= build.label.rjust(3, ' ') rescue build.id %>: <%= I18n.t(build.status.downcase) rescue nil %> </a></b>
									</div>
			                    <% elsif build.status == "scheduled" %>
			                        <div class="build_list_<%= build.status %> project_build_history_item  <% unless idx == 0 %>project_build_history_item_past <% end %>">
									  <span data-localtime-format><%= build.created_at.iso8601 %></span>
										<br/>
			                          <a href="/builds/<%= build.id %>"><%= build.label.rjust(3, ' ') rescue build.id %>: <%= I18n.t(build.status.downcase) rescue nil %> </a>
									</div>
			                    <% else %>
			                        <div class="build_list_other project_build_history_item <% unless idx == 0 %>project_build_history_item_past <% end %>">
									  <span data-localtime-format><%= build.created_at.iso8601 %></span>
										<br/>
			                          <a href="/builds/<%= build.id %>"><%= build.label.rjust(3, ' ') rescue build.id %>:<%= I18n.t(build.status.downcase) rescue nil %> </a>
									</div>
			                    <% end %>
			                <% end %>
			              </div>
			          <% end %>
								
					</div>										
         
        </div>
      </td>
		</tr>
	</table>
</div>

	<div class="col-sm-12 col-md-6  <% if BuildRunner.busy? || ( the_current_user && (the_current_user.is_admin? || the_current_user.has_role?(:builder, project) )) %> <% else %>hidden-mobile<% end %>" style="min-height: 80px;">
		<table width="100%"> 
			<tr>
				<td>
        <% if project.is_building? %>
            <input class="btn btn-warning btn-sm" id="cancel_build_<%= project.id %>" style="margin-top: 20px; color: #FFF; margin-right: 10px;" type="button" value="Cancel this build" <%if the_current_user.nil?%> disabled="true"<% end %>/>
        <% else %>

              <input class="btn btn-default btn-sm not-for-showcase" id="build_project_<%= project.id %>" style="margin-top: 20px;"
                <% if BuildRunner.busy? || the_current_user.nil? || !(the_current_user.is_admin? || the_current_user.has_role?(:builder, project) )   %> disabled="true" <% end %>
               type="button" value="<%= I18n.t(:build_now)%>"/> 							 

							 <% build_server_env = project.config.environment_variables["SERVER"] rescue nil %>
							 <%if !build_server_env.blank? %>
							 <div style="margin-top: 0.4rem;">
							 	<span class="badge badge-primary"><%= build_server_env %></span>
							 </div>
							 <% end %>
        <% end %>

        <script type="text/javascript">

            $("#build_project_<%=project.id%>").click(function(e) {
                // stop normal link click
                e.preventDefault();

								<% unless RACK_ENV == "showcase" %>
                // send request
                $.post("/projects/<%=project.id%>/start_build", function(json) {
									var data = JSON.parse(json);
									console.log(data);
									console.log(data["build_id"]);
									if (data["build_id"]) {
										// redirect to the build page
										window.location = "/builds/" + data["build_id"];
										
									} else {
	                  $("#trigger_response_<%=project.id%>").html(										
	                     "Failed to start a build"
	                  );
									}

                  /* CHANGE, based on Courtney' suggestion, as only one build allowed anyway
									   alwasy redirect to build page, instead refresh home page 
									  location.reload(); 
									*/
                });
								<% end %>
            });

             $("#cancel_build_<%=project.id%>").click(function(e) {
                // stop normal link click
                e.preventDefault();

                // send request
                $.post("/projects/<%= project.last_build_id %>/cancel_build", function(json) {
                    location.reload();
                });
            });
        </script>
        <div id="trigger_response_<%= project.id %>" style="display:none;"></div>
        <!-- display_builder_state(project.builder_state_and_activity -->
      </td>

      <td class="build_details" valign="top" width="500">
        <% latest_build = recent_builds.first %>
        <% if latest_build %>
            <% if latest_build.incomplete? %>
                <div style="margin-top:20px;">
                  Now building: <b><%= latest_build.label %></b>
                  for <b><%= format_seconds(latest_build.elapsed_time_in_progress) %></b>
                  <br>
                  <% if latest_build.stage %>
                      <br>Stage: <%= latest_build.stage %>
                  <% end %>
                  <div id="progressbarWrapper" class="ui-widget-default">
                    <div class="progress">
                      <div class="progress-bar progress-bar-info progress-bar-animated progress-bar-striped bg-warning active" style="width: <%=project.build_progress_percentage %>%">
                      </div>
                      <!-- <div id="progressbar" style="height:100%;"></div> -->
                    </div>
                  </div>
                </div>
            <% end %>
            <br/>
            <% if latest_build.brief_error %>
                <div><a href="/builds/<%=latest_build.id %>" class="failed"><%= latest_build.brief_error %></a></div>
            <% end %>
            <div class="error_message"><%= project.builder_error_message %></div>
        <% end %>
      </td>

	  <td width="24" align="right">
      <div style="width: 22px; padding-left: 10px;">
    		 <%= raw build_poll_image(project) rescue nil %>
    		 <%= raw build_timed_image(project) rescue nil %>
    		 <%= raw ui_test_image(project) %>
    		 <%= raw scm_image(project) rescue nil %>
    		 <%= raw grid_func_test_image(project) %>
				 <% if project.builds.count > 0%>
         <a href="/api/projects/<%= project.identifier%>/status" target="_blank" data-toggle="tooltip" data-placement="left" title="<%= I18n.t(:rss_tooltip)%>" ><i class="fa fa-rss" aria-hidden="true"></i></a>
				 <% end %>
  		 </div>
	  </td>
    </tr>
  </table>
</div>

</div>

<!-- showing charts can be quite expensive, use an environment to cudstomize loading -->
<% max_load_chart_project_count = ENV["BUILDWISE_MAX_HOME_PAGE_PROJECTS_WITH_CHARTS"].to_i rescue 5 %>
<% max_load_chart_project_count = 5 if max_load_chart_project_count < 5 %>
<!-- |<%= max_load_chart_project_count %>|<%= seq %>|-->
<% if true  %>
<script type="text/javascript">
	
	Highcharts.chart('project-chart-<%= project.id%>', {
	    chart: {
	      type: 'column',
        backgroundColor: null
	    },
		  title: {
          text: ''
      },
      credits: {
          enabled: false
      },
      xAxis: {
          labels: {
              enabled: false
          },
          title: {
              text: null
          },
          startOnTick: false,
          endOnTick: false,
          tickPositions: []
      },
      yAxis: {
          endOnTick: false,
          startOnTick: false,
          labels: {
              enabled: false
          },
          title: {
              text: null
          },
          tickPositions: [0]
      },
      legend: {
          enabled: false
      },
	    tooltip: {
         positioner: function () {
            return { x: 0, y: 0 };
         },
				 formatter: function() {
					 return '<span style="font-size:10px">#' + this.point.id  + ' </span> <span style="font-size:10px;"><b>'  + this.point.duration + '</b></span>' + 
					    '  <label style="font-size:10px;"><i> ' +  this.point.pass_rate + '</i></label>' + 
					   '<br/>' + '<span style="font-size:10px">' + this.point.time + '</span>';
				}
	    },
	    plotOptions: {
	        column: {
	            pointPadding: 0.15,
	            borderWidth: 0
	        },
					series: {
            animation: false,
						cursor: 'pointer',
						point: { 
							events: {
								click: function() {
									window.location.href = "/builds/" + this.id;
								}
							}
						}
					}
	    },
      series: [{
          name: 'time',
					maxPointWidth: 10,									
          data: <%= raw project.last_builds(10).reverse.collect{|x| x.chart_data}.to_json %>					
      }]
		});
	
</script>
<% end %>