//=============================================================================
//
//@doc EXTERNAL
//
//@module sheetReporting.js   | Javascript API for ArtCAM
//
// ----------------------------------------------------------------------------
// COPYRIGHT 2005 DELCAM PLC., BIRMINGHAM, ENGLAND. 
// ----------------------------------------------------------------------------
//
// History.
// Who When     What   
// --- -------- ---------------------------------------------------------------
// pah 15/02/05 Written
// pah 16/06/05 Updated for SP2 security, added toolpath summary
//-----------------------------------------------------------------------------

// The print button is removed as IE6 SP2 can block printing from script 
// (because it is not a user action)
// Instead we display IE menu so the user has Print Preview, Print etc...


// Set artcam to be the external interface, we use the topmost document window
// as that is the one that is attached.
var artcam = top.external;

// Shortcut to write variable names into the document
var w=document.write;



function make_sheet_visible( sheet_index )
{
   // Select it
   artcam.VectorSheets.selectedIndex = sheet_index;

   // Empty the vector selection
   artcam.VectorSelection.EmptySelection();

   // Refresh the view
   artcam.Refresh2dView()
}


// Create the sheets report.
//
// if all_sheets is true process all sheets
//               if false process just the selected sheet
function DoSheetReport( all_sheets )
{
   var print_toolpath_summary = true;

	var DirSelector = artcam.CreateFileSelector();
	if (DirSelector == null) {
		alert("Failed to create file selector");
		return;
	}

	var model = artcam.CurrentModel;
	if (model==null) {
		alert("Failed to get current model");
		return;
	}
	
	var root_dir = artcam.HtmlRootDir + "Sheets\\PrintFiles";
	var report_filepath = root_dir + "\\" + "sheet.htm";

	// If the report directory doesn't exist, create it
	if (!DirSelector.DirectoryExists(report_filepath)) {
		if (!DirSelector.CreateDirectory(root_dir)) {
			artcam.MessageBox("Failed to create directory\n" + root_dir);
			return;
		}
	}

	var txt_output = new Array();

   // For each sheet
   var selected = artcam.VectorSheets.selectedIndex;           // Selected sheet
   var last_sheet = artcam.VectorSheets.FindLast();            // Last sheet

   for (var idx = artcam.VectorSheets.FindFirst(); artcam.VectorSheets.IsValid(idx); idx = artcam.VectorSheets.FindNext(idx)) {
      // If selected sheet OR we want all sheets
      if (idx == selected || all_sheets) {
         // Don't output page break after last sheet
         CreateSheetReport( idx, txt_output, root_dir, idx!=last_sheet );
      }
   }

   // Reselect the original sheet, if required
   if (all_sheets) {
      make_sheet_visible( selected );
   }

   // ------------------- Print Button ----------------
   // Disable print button as IE6 SP2 can block printing from script (because it is not a user action)
   // Instead we display menu so the user has Print Preview, Print etc...
	
   // Write HTML string to file
	var output_html = txt_output.join("\n");
	var info_filepath = report_filepath;
	DirSelector.WriteTextFile(info_filepath, output_html);

   // Pop open the file in a window
   window.open(info_filepath, "_blank", "menubar=yes,titlebar=no,toolbar=no,scrollbars=yes, height=700, width=540");
}



//=== CreateSheetReport =======================================================
//
// Create report for a specified sheet
//
// History
// Who When     What
// --- -------- ---------------------------------------------------------------
// pah 06/09/07 Written
//-----------------------------------------------------------------------------
function CreateSheetReport( sheet_index,     // Sheet to report
                                 txtArr,     // Array to push HTML output
                             image_root,     // Root for sheet image
                          end_page_break     // If true add page break at end
                           )
{
   // Make the required sheet visible
   make_sheet_visible( sheet_index );

	var display_image_filepath = image_root +  "\\SheetImageDisplay" + sheet_index + ".bmp";

   var bitmap = artcam.CreateEmptyBitmap();
   if (bitmap != null) {

      // display bitmap
      var width = 600;       
      var height = width*3/5;
      if (!bitmap.CreateFromCurrentView(width,height,true,true,true,255,255,255)) {
         alert('failed to create bitmap');
      } else {
         if (!bitmap.Save(display_image_filepath))
            alert('failed to save bitmap');
      }
      bitmap = null;
   }

	txtArr.push("<html>");
	txtArr.push("<head>");
	txtArr.push("<style type='text/css' media='screen'>");
	//txtArr.push("BODY{background-color:#FFFFFF; font-family:arial,helvetica; text-align:justify; color:black;}");
	txtArr.push("H1{FONT-WEIGHT:bold; FONT-SIZE:16pt; COLOR: #FFFFFF; BACKGROUND-COLOR: #345789; FONT-FAMILY: Arial, Helvetica, sans-serif; TEXT-ALIGN:center;}");
	txtArr.push("H2{FONT-WEIGHT:bold; FONT-SIZE:14pt; COLOR:#345789; FONT-FAMILY:Arial, Helvetica, sans-serif; TEXT-ALIGN:left; margin-bottom:0; margin-top:6; TEXT-ALIGN:center;}");
	txtArr.push("H3{FONT-WEIGHT:bold; FONT-SIZE:22pt; COLOR:#000000; FONT-FAMILY:Arial, Helvetica, sans-serif; TEXT-ALIGN:left; margin-bottom:0; margin-top:6;}");
   txtArr.push(".invisibleprint{display:;}");
   txtArr.push(".invisibledisplay{display:none;}");
	txtArr.push("</style>");

	txtArr.push("<style type='text/css' media='print'>");
	//txtArr.push("BODY{background-color:#FFFFFF; font-family:arial,helvetica; text-align:justify; color:black;}");
	txtArr.push("H1{FONT-WEIGHT:bold; FONT-SIZE:16pt; COLOR: #000000; FONT-FAMILY:Arial, Helvetica, sans-serif; TEXT-ALIGN:left;}");
	txtArr.push("H2{FONT-WEIGHT:bold; FONT-SIZE:14pt; COLOR:#345789;  FONT-FAMILY:Arial, Helvetica, sans-serif; TEXT-ALIGN:left; margin-bottom:0; margin-top:6; TEXT-ALIGN:center;}");
	txtArr.push("H3{FONT-WEIGHT:bold; FONT-SIZE:22pt; COLOR:#000000;  FONT-FAMILY:Arial, Helvetica, sans-serif; TEXT-ALIGN:left; margin-bottom:0; margin-top:6;}");
	txtArr.push("P.breakhere {page-break-before: always}");
   txtArr.push(".invisibleprint{display:none;}");
   txtArr.push(".invisibledisplay{display:;}");
	txtArr.push("</style>");
	txtArr.push("</head>\n<body>");


   // -------------- page header ------------------------
	txtArr.push("<table cellspacing=0 cellpadding=0 width=100% border=0>");
	txtArr.push("<tr>");
   txtArr.push("<td><H3>" + gPageName + "</H3></td>");
   //txtArr.push("<td align=right><img src='" + image_root + "\\SheetTitleImage.gif' ></td>");
   txtArr.push("<td></td>");
	txtArr.push("</tr>");
	txtArr.push("</table>\n\n");

   // -------------- model name + sheet name + image -------------------------

	txtArr.push("<H1><b>" + artcam.CurrentModel.ModelName + "</b></H1>");

   var sheetObj = artcam.VectorSheets.GetSheet(sheet_index);
	txtArr.push("<H1><b>" + sheetObj.Name + "</b></H1>");


//	txtArr.push("<table id=summary_table cellspacing=0 cellpadding=0 border=0 width=100%>");
   //	txtArr.push("<tr><td align=left><img src='" + display_image_filepath + "' style ='height:80mm';></td></tr>");
//	txtArr.push("<tr><td align=left><img src='" + display_image_filepath + "'></td></tr>");
//	txtArr.push("</table>\n\n");

 	txtArr.push("<img src='" + display_image_filepath + "'>");


   // ----- display panel data -------------------------

	txtArr.push("<H1><b>" + gSheetData + "</H1>");

   var width  = artcam.CurrentModel.RealWidth;
   var height = artcam.CurrentModel.RealHeight;
   var material = sheetObj.Material;

   // Get our Units
   var units = Units();
  
   //txtArr.push(gJobConsistsOf + ' ' + 1 + ' ' + gNumSheetsDefined + '<p>');

   txtArr.push('<table  cellspacing=0 cellpadding=0 border=0>');

   txtArr.push('<tr><td><b>' + gSheetMaterial  + ':&nbsp</b></td><td> ' + material + '</td></tr>');
   txtArr.push('<tr><td><b>' + gSheetWidth  + ':&nbsp</b></td><td> '  + Round(width,3)    + '&nbsp;' + units + '</td></tr>');
   txtArr.push('<tr><td><b>' + gSheetHeight + ':&nbsp</b></td><td> ' + Round(height,3)    + '&nbsp;' + units + '</td></tr>');

   if ( artcam.MaterialDefined ) {
      material_maxZ = artcam.MaterialMaxZ;
      material_minZ = artcam.MaterialMinZ;
      material_thickness = Math.abs(material_maxZ - material_minZ);

      // Don't display thickness as it may not be correct
      // (we are transitioning from a fixed model thickness to a per sheet thickness)
      //txtArr.push('<tr><td><b>' + gMaterialThickness + ':&nbsp</b></td><td> ' + Round(material_thickness,3)    + '&nbsp;' + units + '</td></tr>');

      var origin_text = gsmBottomOfBlockText;
      if (material_minZ < 0)
         origin_text = gsmTopOfBlockText;

      txtArr.push('<tr><td><b>' + gMaterialZZero + ':&nbsp</b></td><td> ' + origin_text + '</td></tr>');
   }

   txtArr.push("</table><br>\n");

   // ------------ toolpaths -----------------------
   if ( true ) {

	   txtArr.push("<H1><b>" + gToolpathData + "</b></H1>");  // style='page-break-before:always;'

      g_toolpath_data = "<table cellspacing=0 cellpadding=0 border=0 >\n";
      var count = artcam.ToolpathCount;
      var num_toolpaths = 0;

      for (var cur_toolpath_idx = 0; cur_toolpath_idx < count; cur_toolpath_idx++ ) {
         var toolpath = artcam.GetToolpath(cur_toolpath_idx);
         // If toolpath is on sheet...
         if (toolpath.Sheet == sheet_index) {
            g_toolpath_data += "<tr><td colspan=2><b>" + toolpath.Name + "</b></td></tr>\n";
            //WriteToolpathAndChildrenInformation(toolpath);
            g_toolpath_data += "<tr><td colspan=2></td></tr>\n";
         }
      }
      g_toolpath_data += "</table>"
      txtArr.push(g_toolpath_data);
      g_toolpath_data = "";
   }
   
   // Do we want a page break?
   if (end_page_break)
      txtArr.push( "<P CLASS='breakhere'>" );
}



// === WriteToolpathAndChildrenInformation ====================================
//
// Write description for toolpath and children
//
function WriteToolpathAndChildrenInformation(toolpath)
{
   var num_children = toolpath.GetNumberOfChildren();
   if (num_children > 0) {
      for (var n = 0; n < num_children; n++) {
         var child_toolpath = toolpath.GetChild(n);
         WriteToolpathAndChildrenInformation(child_toolpath);
      }
   } else {
      WriteToolpathInformation(toolpath);
   }
}


// === WriteToolpathInformation ===============================================
//
// Add information on passed toolpath to passed string
//
function WriteToolpathInformation(toolpath)
{
  var tool = toolpath.GetTool();

  var units = Units();
  units = " " + units;

  var feed_units = toolpath.FeedrateUnits;
  var feed_units_string = " ";
  switch (feed_units)
     {
     case 0:
          feed_units_string += gstMM_Sec;
          break;
     case 1:
          feed_units_string += gstMM_Min;
          break;
     case 2:
          feed_units_string += gstM_Min;
          break;
     case 3:
          feed_units_string += gstINCH_Sec;
          break;
     case 4:
          feed_units_string += gstINCH_Min;
          break;
     case 5:
          feed_units_string += gstFEET_Min;
          break;
     } 

   g_toolpath_data += "\n";
//   g_toolpath_data += "<tr><td colspan=3>&nbsp;&nbsp;</td></tr>\n";
   g_toolpath_data += "<tr>\n";
   g_toolpath_data += "<ul></ul>\n";
   g_toolpath_data += "<td>" + toolpath.ToolDescription + "</td>\n";
   g_toolpath_data += "<td>" + gstToolNumber + "</td><td>" + toolpath.ToolNumber + "</td>\n";
   g_toolpath_data += "</tr>\n";
// g_toolpath_data += "<tr><td></td><td>Est. Machining Time:&nbsp;&nbsp;</td><td><b>" + toolpath.EstimatedMachiningTime + "</b></td><td colspan=3></td></tr>\n";
// g_toolpath_data += "<tr><td></td><td>Machining Area:&nbsp;&nbsp;</td><td colspan=5>Width:<b>" + Round(toolpath.BoundingBoxXLength,3) + "</b>&nbsp;Height:<b>" + Round(toolpath.BoundingBoxYLength,3) + "</b>&nbsp;Depth:<b>" + Round(toolpath.BoundingBoxZLength,3) + "</b></td></tr>\n";
  
//g_toolpath_data += "<tr><td></td><td>" + gstFeedRateText   + ":&nbsp;&nbsp;</td><td><b>" + toolpath.Feedrate + feed_units_string + "</b></td><td colspan=3></td></tr>\n";
//g_toolpath_data += "<tr><td></td><td>" + gstPlungeRateText + ":&nbsp;&nbsp;</td><td><b>" + toolpath.Plungerate + feed_units_string  + "</b></td><td colspan=3></td></tr>\n";
//g_toolpath_data += "<tr><td></td><td>" + gstSpindleText    + ":&nbsp;&nbsp;</td><td><b>" + toolpath.SpindleSpeed + " " + gstRPM + "</b></td><td colspan=3></td></tr>\n";

//g_toolpath_data += "<tr><td></td><td>" + gHomePositionFieldName + "&nbsp;&nbsp;</td><td>X:<b>" + Round(toolpath.HomePositionX,3) + "</b>&nbsp;Y:<b>" + Round(toolpath.HomePositionY,3) + "</b>&nbsp;Z:<b>" + Round(toolpath.HomePositionZ,3) + "</b></td></tr>\n";
//g_toolpath_data += "<tr><td></td><td>" + gSafeZFieldName        + "&nbsp;&nbsp;</td><td><b>" + Round(toolpath.SafeZ,3) + "</b></td><td colspan=3></td></tr>\n";
}
