//=============================================================================
//
// ProjectManager.js
//
// Methods for managing projects
//
// ----------------------------------------------------------------------------
// COPYRIGHT 2005 DELCAM PLC., BIRMINGHAM, ENGLAND.
// ----------------------------------------------------------------------------
//
// History.
// Who When     What
// --- -------- ---------------------------------------------------------------
// pah 24/02/05 Added this header, add project to MRU project list
// sic 27/07/05 Now uses new OA_Options object to get and set project path.
// sgc 14/08/06 A new project will now have the blue 'ArtCAM' background image as default
// sgc 13/12/06 Corrected 3pd to 3dp for import
//-----------------------------------------------------------------------------


function OnProjectOpen(filepath)
{
   artcam.OpenJewelSmithProject(filepath);
}

//=== SaveArtFile ==============================================
//
// Saves the current .art file with a filename generated automatically
// according to the passed folder string.
//
// History
// Who When     What
// --- -------- ---------------------------------------------------------
// ejp 30/09/02 Written
// ejp 01/10/03 If the folder doesn't exist, create it
// sic 23/01/08 Hijacked.  The model is now automatically added to the
//              project with an arbitrary title.  This function just
//              renames the model now.
//-----------------------------------------------------------------------

function SaveArtFile(folder, filename)
{
   artcam.CurrentModel.Rename(filename, false);
   //artcam.CurrentModel.MoveTo(folder);
   artcam.CurrentModel.Save();
}


//=== OpenArtFile ==============================================
//
// Opens the .art file associated with the passed folder string.
//
// History
// Who When     What
// --- -------- ---------------------------------------------------------
// ejp 30/09/02 Written
//-----------------------------------------------------------------------

function OpenArtFile(folder)
{
   if(!artcam.ProjectAssemblyExists())
      return false;

   var filepath = "";

   var project_directory = artcam.ProjectAssembly.GetString("ringinfo_project_dir", "failed");

   var fs = artcam.CreateFileSelector();
   if(fs == null)
   {
      artcam.Alert("OpenArtFile::Unable to create FileSelector",0);
      return;
   }

   // If the filepath string is empty then kick-off browser
   if(typeof(filepath)=="undefined" || filepath=="")
   {
      fs.AddFileFilterString(gArtFile,"art");
      fs.SetDefaultFileType("art");
      var directory = project_directory + folder + "\\";
      fs.SetDefaultDirectory(directory);

      if(!fs.FileLoad(gLoadProjectComponent,filepath))
         return;

      filepath = fs.SelectedPath();
   }
   // Otherwise check if the requested file exists
   else if(!fs.FileExists(filepath))
   {
      artcam.Alert("OpenArtFile::The file - '" + filepath + "' does not exist",0);
      return;

   }

   var page_tab_index = artcam.CurrentTab;
   if(artcam.ModelLoaded)
   {
      if(!artcam.FileClose())
         return false;
   }

   var oa_model = artcam.OpenExistingModel(filepath);
   if(oa_model==null)
   {
      artcam.Alert("OpenArtFile::There is no existing " + folder + " in this job",0);
      return false;
   }
   artcam.CurrentTab = page_tab_index;
   return true;
}

function CreateNewProject(name)
{
   // do we have an existing job with this name ?
   var DirSelector = artcam.CreateFileSelector();
   if (DirSelector == null)
      return false;

   var JobRootDirectory = GetJobRoot();
   if(JobRootDirectory=="")
      return false;

   // check if directory already exists ..
   var new_directory_path = JobRootDirectory + name;

   if (DirSelector.DirectoryExists(new_directory_path))
   {
      if(confirm(gOverwriteProject))
         DirSelector.DeleteDirectory(new_directory_path);
      else
         return false;
   }

   // the directory for this job does not exist - create the directory
   if (!DirSelector.CreateDirectory(new_directory_path))
   {
      artcam.MessageBox(gFailedToCreateDir + "\n" + new_directory_path);
      return false;
   }
   /*
   if (!DirSelector.CreateDirectory(new_directory_path+"\\Shank"))
   {
      artcam.MessageBox(gFailedToCreateDir1 + "\n" + new_directory_path + "\n" + gFailedToCreateDir2 + name);
      return false;
   }
   if (!DirSelector.CreateDirectory(new_directory_path+"\\Head"))
   {
      artcam.MessageBox(gFailedToCreateDir1 + "\n" + new_directory_path + "\n" + gFailedToCreateDir2 + name);
      return false;
   }
   */

   if(artcam.ProjectAssemblyExists())
      artcam.DeleteProjectAssembly();

   var proj_path = new_directory_path + "\\" + name + ".3DP";

   artcam.CreateProjectAssembly();

   // Set the default background to be ArtCAM
   var material = artcam.SelectedAssembly.GetMaterial();
   if (material == null)
      {
      material = artcam.Material;
      artcam.SelectedAssembly.SetMaterial(material);
      material = artcam.SelectedAssembly.GetMaterial();
      }

   material.backgroundImageName = "ArtCAM";
   material.Apply();
   artcam.SelectedAssembly.SetMaterial(material);
   artcam.Refresh3dView();

   //projectinfo.StoreRingInfoInAssembly(artcam.ProjectAssembly);
   artcam.ProjectAssembly.SetString("ringinfo_project_dir", new_directory_path + "\\");
   artcam.ProjectAssembly.Name = name;
   artcam.ProjectAssembly.Save3dAssembly( proj_path );
   artcam.ProjectAssembly.UpdateAssemblyMonitor();
   artcam.ProjectAssembly.InDisplayList=true;
   artcam.ProjectAssembly.SetString("jewelsmith_project_version", "7.1");

   // Add to MRU list
   artcam.AddToMRUProjects( proj_path );

   return true;
}



//=== SetJobRoot ==============================================
//
// Brings up a file selector dialog to allow the user to choose
// a root directory in which all the project folders will be created.
// The directory path is stored in the registry and returned as a string.
//
// History
// Who When     What
// --- -------- ---------------------------------------------------------
// ejp 30/09/02 Written
//-----------------------------------------------------------------------

function SetJobRoot()
{
   var job_root = "";
   var DirSelector = artcam.CreateFileSelector();
   if (DirSelector == null)
      return job_root;

   // ejp 15/08/05 this string is in NewProject.atext, but should be in Common.atext
   // because of translation it is too late to move this now, this catch is temporary fix for 8.1
   if(typeof(gSelectProjectDirectory) == 'undefined')
      gSelectProjectDirectory = " ";

   DirSelector.ExistingDirectory(gSelectProjectDirectory,artcam.options.JewelSmithProjectPath);
   if (DirSelector.DirectorySelected)
   {
      job_root = DirSelector.SelectedPath;
      job_root += "\\";
//      artcam.StoreString("RingInformation","Job_root_dir",job_root);
      artcam.options.JewelSmithProjectPath = job_root;
      return job_root;
   }
   return job_root;
}


//=== GetJobRoot ==============================================
//
// Returns the current root directory in which the project folders will be created etc.
// This is stored in the registry.
// If no root directory is set then it calls SetJobRoot()
//
// History
// Who When     What
// --- -------- ---------------------------------------------------------
// ejp 30/09/02 Written
//-----------------------------------------------------------------------

function GetJobRoot()
{
//   var job_root = artcam.RetrieveString("RingInformation","Job_root_dir", "");
   var job_root = artcam.options.JewelSmithProjectPath;
   if(job_root=="")
      job_root = SetJobRoot();
   return job_root;
}

function GotoRingCreationPage()
{
   if(!artcam.ModelLoaded)
   {
      // This shouldn't really happen
      artcam.Alert("GotoRingCreationPage: No model loaded",0);
      return;
   }

   var model_creation_page_name = "";

   // Find out if this is a JewelSmith model
   if(artcam.CurrentModel.StringExists("Ring_creation_page_name"))
   {
      model_creation_page_name = artcam.CurrentModel.GetString("Ring_creation_page_name", "Failed");
      var model_component_type = artcam.CurrentModel.GetString("Ring_component_type", "Failed");
   }
   // set the common root
   var creation_page = artcam.HtmlRootDir() + "..\\..\\Custom\\HTML\\";

   switch(model_creation_page_name)
   {
   case "RotaryAxis":
   case "RotaryAxisSetting":
      creation_page += "RotaryAxisTools\\RotaryAxisToolsFrame.htm";
      break;
   case "RoundCluster":
      creation_page += "RoundCluster\\RoundClusterFrame.htm";
      break;
   default: // Not a JewelSmith model - goto general tools
      creation_page += "GeneralTools\\GeneralToolsFrame.htm";
   }

   // Check the page exists and go to it.
   var oa_file_selector = artcam.CreateFileSelector();
   if(oa_file_selector.FileExists(creation_page))
   {
      artcam.DisplayPageInCustomTab(creation_page,0);
      return;
   }
   artcam.Alert("GotoRingCreationPage: Failed to find creation page - " + creation_page,0);
}

function SaveReliefFile(relief, folder, filename)
{
   if(!artcam.ProjectAssemblyExists())
      return false;

   // Create a default filename if one isn't specified
   if(typeof(filename)=="undefined" || filename=="")
   {
      filename = folder + ".rlf";
   }


   var splitpath = artcam.CreateSplitPath(filename);
   var extension = splitpath.Extension;
   if(extension.toLowerCase!="rlf")
      splitpath.Extension = "rlf";

   var project_directory = artcam.ProjectAssembly.GetString("ringinfo_project_dir", "failed");

   var filepath = project_directory + folder + "\\" + filename ;

   var fs = artcam.CreateFileSelector();
   if(fs == null)
   {
      artcam.Alert("SaveReliefFile::Unable to create FileSelector",0);
      return false;
   }

   // If the file exists then kick-off browser
   if(fs.FileExists(filepath))
   {
      fs.AddFileFilterString(gReliefFile,"rlf");
      fs.SetDefaultFileType("rlf");
      var directory = project_directory + folder + "\\";
      fs.SetDefaultDirectory(directory);

      if(!fs.FileSave(gSaveReliefComponent,filepath))
         return false;

      filepath = fs.SelectedPath();
      relief.SaveAs(filepath);
   }
   else
   {
      relief.SaveAs(filepath);
   }

   return true;
}

function StoreCreationFilePathInAssembly(assembly)
{
   if(!artcam.ModelLoaded)
      return false;

   if(!artcam.ProjectAssemblyExists())
      return false;

   var file = GetRelativePath();

   if(file=="")
      return false;

   assembly.SetString("CreationFile", file);
}

function GetRelativePath()
{
   var project_directory = artcam.ProjectAssembly.GetString("ringinfo_project_dir", "failed");
   if(project_directory=="failed")
      return "";

   var model_path = artcam.CurrentModel.Filename;
   var elements = model_path.split(project_directory);

   if(elements.length==0)
      return "";

   return elements[1];
}

function OnProjectSave()
{
   artcam.DoCommand(ID_JS_SAVE_PROJECT);
}

function OnCreateProjectFrom3DModel(filepath)
{
   var fs = artcam.CreateFileSelector();
   if(fs == null)
   {
      artcam.Alert("OnCreateProjectFrom3DModel::Unable to create FileSelector", 0);
      return;
   }

   // If the filepath string is empty then kick-off browser
   if(typeof(filepath)=="undefined" || filepath=="")
   {
      fs.AddFileFilterString(gModelFiles,"*.3DS;*.STL;*.DXF;*.3DA;*.3DP;*.DMT");
      //fs.SetDefaultFileType("STL");
      fs.SetDefaultDirectory(GetJobRoot());

      if(!fs.FileLoad(gImport3DModelFile,filepath))
         return false;

      filepath = fs.SelectedPath();
   }
   // Otherwise check if the requested file exists
   else if(!fs.FileExists(filepath))
   {
      artcam.Alert("OnCreateProjectFrom3DModel::The file - '" + filepath + "' does not exist",0);
      return false;

   }
   var splitpath = artcam.CreateSplitPath(filepath);
   var extension = splitpath.Extension;
   var name = splitpath.File;
   CreateNewProject(name);
   artcam.ProjectAssembly.SetString("ringinfo_project_dir", GetJobRoot() + "\\" + name + "\\");

   if(!artcam.ProjectAssemblyExists)
      return false;

   var new_assembly = artcam.CreateAssembly(name);
   if (new_assembly == null)
   {
      artcam.MessageBox(gFailedToCreateAssembly);
      return;
   }

   switch(extension.toLowerCase())
   {
   case "stl":
   case "3ds":
   case "dxf":
   case "dmt":
      var temp_mesh = artcam.Create3dModelInfo();
      if(temp_mesh==null)
      {
         // Internal error only
         artcam.Alert("OnCreateProjectFrom3DModel::Failed to create model",0);
         return false;
      }
      if(!temp_mesh.LoadSpecific3dModel(name, splitpath.Path, extension))
      {
         artcam.MessageBox(gFailedtoloadModel);
         return false;
      }
      temp_mesh.Name = name;
      new_assembly.Append3dModel(temp_mesh);
      temp_mesh.InDisplayList=false;
      temp_mesh = null;
      break;

   case "3dp":
   case "3da":
      if(!new_assembly.Load3dAssembly(filepath))
      {
         artcam.MessageBox(gFailedtoLoadModel);
         return false;
      }
      break;

   default:
      artcam.MessageBox(gUnknownfiletypeselected);
      return false;
   }
   new_assembly.InDisplayList=false;
   artcam.ProjectAssembly.AppendChild(new_assembly);
   artcam.ProjectAssembly.UpdateAssemblyMonitor();
   OnProjectSave();
   artcam.Refresh3dView();
   return true;
}

function OnImportMesh(filename)
{
   var extension;
   // if the filetype is not provided, use the file browser

   // create a file browser and get a filename to load from
   var file_browser = artcam.CreateFileSelector();
   if (file_browser == null)
      return;

   if(!file_browser.FileExists(filename))
   {

      file_browser.AddFileFilterString(gModelFiles,"*.3DS;*.STL;*.DXF;*.3DA;*.3DP;*.DMT");
      //fs.SetDefaultFileType("STL");
      file_browser.SetDefaultDirectory(GetJobRoot());

      if(!file_browser.FileLoad("Import 3D Model File",""))
         return false;


      var pathname  = file_browser.SelectedPath;
      var splitter = artcam.CreateSplitPath(pathname);

      //extension = file_browser.SelectedExtension;
      var title     = file_browser.SelectedTitle;
      var file_type = file_browser.SelectedType();


      if (pathname == "")
      {
         artcam.MessageBox(gNoName);
         return;
      }

      filename = pathname;
   }

   var splitter = artcam.CreateSplitPath(filename);
   extension = splitter.Extension;

   switch (extension.toLowerCase())
   {
   case "3da":
   case "3dp":

      var new_assembly = artcam.CreateAssembly("");
      if (new_assembly == null)
      {
         artcam.MessageBox('artcam.CreateAssembly() - failed');
         return;
      }
      if (!new_assembly.Load3dAssembly(filename))
      {
         new_assembly = null;
         artcam.MessageBox('Load3dAssembly - failed');
         return false;
      }
      artcam.ProjectAssembly.AppendChild(new_assembly);
      new_assembly.InDisplayList=false;
      break;

   case "stl":
   case "3ds":
   case "dxf":
      var temp_mesh = artcam.Create3dModelInfo();
      if(temp_mesh==null)
      {
         artcam.MessageBox(gFailedtoCreateModel);
         return false;
      }
      if(!temp_mesh.LoadSpecific3dModel(title, filename, extension))
         artcam.MessageBox(gFailedtoLoadModel);
      temp_mesh.Name = splitter.File;
      artcam.SelectedAssembly.Append3dModel(temp_mesh);
      temp_mesh.InDisplayList=false;
      temp_mesh = null;
      break;

   case "dmt":

      var new_assembly = artcam.CreateAssembly(splitter.File);

      if (new_assembly == null)
      {
    artcam.MessageBox('artcam.CreateAssembly() - failed');
         return;
      }

      if (!new_assembly.LoadDMT(filename))
      {
         new_assembly = null;
         artcam.MessageBox('LoadDMT - failed');
         return false;
      }

      artcam.ProjectAssembly.AppendChild(new_assembly);
      new_assembly.InDisplayList=false;

      break;

   default:

      artcam.MessageBox(gUnknownfiletypeselected);
      return false;
   }

   artcam.ProjectAssembly.UpdateAssemblyMonitor();
}
