/**
 * Add custom properties to all templates in a folder.<br>
 * Copyright (c) 2004 Izyn Technologies
 *
 * @author Richard Norton
 */

package izyndoc;

import com.jacob.com.*;
import java.io.*;

public class AddWordCustomProperties
{
  private Error anError;
  private Word wordApp;
  private WordDocuments wordDocs;
  private WordDocument wordDoc;
  private WordDocCustomProps docCustomProps;
  private int docCustomPropsCount;
  private String[] docCustomPropsArray;
  private WordDocCustomProperty docCustomProp;
  private boolean existsAlready = true;
  protected boolean gotWord = false;

  /**
   * Constructor.
   */
  public AddWordCustomProperties()
  {
    try
    {
      ComThread.InitSTA();

      //create an instance of Word
      wordApp = new Word();
      gotWord = true;
    }
    catch (ComFailException cfe)
    {
      String[] errorDetails = {"AddWordCustomProperties"
        , "AddWordCustomProperties()"
        , Constant.WORDOBJECTFAIL + "\n" + cfe.getMessage()};
      //"Can't get object clsid from progid" means Word not installed,
      //also get "can't co-create object".
      anError = new Error(errorDetails, Constant.WORDOBJECT);
      ComThread.Release();
    }
    catch (UnsatisfiedLinkError ule)
    {
      String[] errorDetails = {"AddWordCustomProperties"
        , "AddWordCustomProperties()"
        , Constant.JACOBDLLFAIL + "\n" + ule.getMessage()};
      //"Can't get object clsid from progid" means Word not installed.
      anError = new Error(errorDetails, Constant.WORDOBJECT);
      ComThread.Release();
    }
  }

  /**
   * Close Word.
   */
  protected void closeWord()
  {
    wordApp.quit(new Variant[] {});
    ComThread.Release();
  }

  /**
   * Add custom properties to Word Documents if they aren't there already.
   *
   * @param aWordDoc File a Word document or template
   */
  protected void addWordDocCustomProperties(File aWordDoc)
  {
    String templateFullPath;
    String message;
    File theWordDoc;

    try
    {
      //get full path to template
      templateFullPath = aWordDoc.getAbsolutePath();
      theWordDoc = new File(templateFullPath);

      //check it exists (you never know)
      if (theWordDoc.exists())
      {
        try
        {
          //get the documents collection
          wordDocs = wordApp.getDocuments();

          //open the template
          wordDoc = new WordDocument(wordDocs.open(templateFullPath));

          //get the CustomDocumentProperties collection
          docCustomProps =
              new WordDocCustomProps(wordDoc.getCustomDocumentProperties());
          //get the CustomDocumentProperties collection count
          docCustomPropsCount = docCustomProps.getCustomPropsCount();

          //for speed put all custom properties into an array
          docCustomPropsArray = new String[docCustomPropsCount];

          //NOTE: 'item' starts at 1
          for (int docCustomPropsItem = 0;
               docCustomPropsItem < docCustomPropsCount;
               docCustomPropsItem++)
          {
            docCustomPropsArray[docCustomPropsItem] =
                  new WordDocCustomProperty(
                  docCustomProps.getCustomProperty(docCustomPropsItem + 1))
                                      .getCustomPropertyName();
          }

          //go through all custom properties in array from root.xml
          for (int newPropsPos = 0;
               newPropsPos < IzynStart.customProps.length;
               newPropsPos++)
          {
            existsAlready = false;

            //go through all current docs custom properties in array
            for (int oldPropsPos = 0;
                 oldPropsPos < docCustomPropsArray.length;
                 oldPropsPos++)
            {
              //compare them
              if (IzynStart.customProps[newPropsPos]
                  .equalsIgnoreCase(docCustomPropsArray[oldPropsPos]))
              {
                //set default value
                new WordDocCustomProperty(
                    docCustomProps.getCustomProperty(oldPropsPos + 1))
                    .setCustomPropertyValue(
                    "[" + IzynStart.customProps[newPropsPos] + "]");

                existsAlready = true;
                //escape the loop
                oldPropsPos = docCustomPropsArray.length;
              }
            }

            //not found
            if (!existsAlready)
            {
              //add a custom property
              docCustomProp =
                  new WordDocCustomProperty(docCustomProps.addCustomProperty
                  (IzynStart.customProps[newPropsPos]
                  , "[" + IzynStart.customProps[newPropsPos] + "]"));
            }
          }

          //set 'saved' to false so Word thinks doc is 'dirty'
          wordDoc.dirtyDoc();

          //save and close the template
          wordDoc.close(Word.SAVE);

          message = "Updated: " + aWordDoc.getName();
        }
        catch (Exception e)
        {
          //keep Word invisible
          wordApp.setVisible(false);

          //close the template without saving
          wordDoc.close(Word.DO_NOT_SAVE);

          message = "Template may be open: " + aWordDoc.getName();
        }
      }//end:if (new File(templateFullPath).exists())
      else
      {
        message = "Template missing: " + aWordDoc.getName();
      }

      //let the user know what was successfull
      String[] successDetails = {"AddWordCustomProperties"
        , "addWordDocCustomProperties()", message};
      anError = new Error(successDetails, Constant.UPDATECUSTOMPROPS);
    }
    catch (ComFailException cfe)
    {
      String[] errorDetails = {"AddWordCustomProperties"
        , "addWordDocCustomProperties()"
        , Constant.WORDDISPATCHFAIL
        + "\n[Path = " + aWordDoc.getName() + "]"
        + "\n" + cfe.getMessage()
        + "\nWord version: " + wordApp.getVersion()};
      anError = new Error(errorDetails, Constant.DISPATCHFAIL);
    }
  }
}