//@include lib_Class.js
//@include lib_sol.common.ObjectFormatter.js
//@include lib_sol.common.ix.FunctionBase.js
//@include lib_sol.common.StringUtils.js

/**
 * Base class to generate filing structures by templates
 *
 * A sub class must implement the methods getTemplateId
 *
 * @author JHR, ELO Digital Office GmbH
 * @version 1.01.001
 *
 * @eloix
 * @requires  sol.common.JsonUtils
 * @requires  sol.common.ix.RfUtils
 * @requires  sol.common.WfUtils
 * @requires  sol.common.ix.FunctionBase
 *
 */

sol.define("sol.contact.ix.functions.GenerateFilingStruct", {
  extend: "sol.common.ix.FunctionBase",

  /**
   * @cfg {String} objId
   * Object ID of destination object
   */

  process: function () {
    var me = this,
        filingstructureTemplate, filingstructureTemplateId,
        filingstructure, date;

    me.readObject();

    filingstructureTemplateId = me.getTemplateId();

    if (filingstructureTemplateId) {
      date = new Date();

      filingstructureTemplate = sol.create("sol.common.Template", {});
      filingstructureTemplate.load(filingstructureTemplateId);
      filingstructure = filingstructureTemplate.apply({
        sord: me.templateSord,
        date: {
          date: date.getDate(),
          day: date.getDay(),
          fullYear: date.getFullYear(),
          hours: date.getHours(),
          milliseconds: date.getMilliseconds(),
          minutes: date.getMinutes(),
          month: date.getMonth(),
          seconds: date.getSeconds(),
          UTCdate: date.getUTCDate(),
          UTCday: date.getUTCDay(),
          UTCfullYear: date.getUTCFullYear(),
          UTChours: date.getUTCHours(),
          UTCmilliseconds: date.getUTCMilliseconds(),
          UTCminutes: date.getUTCMinutes(),
          UTCmonth: date.getUTCMonth(),
          UTCseconds: date.getUTCSeconds()
        }
      });
      if (filingstructure) {
        me.moveToPath(filingstructure);
      }
      return JSON.stringify({ filingstructure: filingstructure });
    }
    return JSON.stringify({ filingstructure: "" });
  },

  /**
   * @private
   */
  readObject: function () {
    var me = this,
        templateSordFormatter;
    
    if (!me.objId) {
      throw "Object ID is empty";
    }
    me.sord = ixConnect.ix().checkoutSord(me.objId, SordC.mbAll, LockC.NO);
    templateSordFormatter = sol.create("sol.common.ObjectFormatter.TemplateSord", { data: me.sord, config: { sordKeys: ["name"], objKeys: [], mapKeys: [] } });
    me.templateSord = templateSordFormatter.build();
  },

  /**
   * @abstract
   * Must return the Object ID of the template.
   */
  getTemplateId: function () {
    throw "Can't call abstract method 'getTemplateId()'";
  },

  /**
   * @private
   * Reads the template name from generator field and determinates the object ID of the template.
   * @param {de.elo.ix.client.Sord} sord
   * @param {String} templateNameField
   * @param {String} templateFolderId
   * @return {String}
   */
  getFilingStructTemplateId: function (sord, templateNameField, templateFolderId) {
    var templateName;
    if (!templateNameField) {
      return null;
    }
    templateName = sol.common.SordUtils.getObjKeyValue(sord, templateNameField);
    if (!templateName) {
      return null;
    }
    if (!templateFolderId) {
      return null;
    }
    return sol.common.RepoUtils.getObjIdFromRelativePath(templateFolderId, "/" + templateName);
  },

  /**
   * @private
   * Moves the element to a new path location.
   * @param {String} filingstructure
   */
  moveToPath: function (filingstructure) {
    var me = this,
        objId = me.objId,
        sord = ixConnect.ix().checkoutSord(objId, EditInfoC.mbSord, LockC.NO).sord,
        regId, oldParentId, sordType, pathSord, pathSordParent, pathReg, lastPos;

    sordType = 3;
    pathSord = sol.common.RepoUtils.getPathFromObjId(sord.id, { separator: "¶" });
    lastPos = pathSord.lastIndexOf("¶");
    pathSordParent = pathSord.slice(0, lastPos);
    if (!sol.common.StringUtils.isBlank(filingstructure)) {
      pathSord = pathSordParent + "¶" + filingstructure + "¶" + sord.name;
      pathReg = pathSordParent + "¶" + filingstructure;
    } else {
      pathSord = pathSordParent + "¶" + sord.name;
      pathReg = pathSordParent;
    }
    regId = sol.common.RepoUtils.preparePath(pathReg, { sordType: sordType });

    if (!regId) {
      me.logger.error(["could not resolve pathReg: {0}", pathReg]);
      throw "could not resolve pathReg: " + pathReg;
    }
    oldParentId = ixConnect.ix().checkoutSord(objId, EditInfoC.mbOnlyId, LockC.NO).sord.parentId;
    me.logger.info(["move sord: ({0}) from -> ({1}) to ({2})", objId, oldParentId, regId]);
    ixConnectAdmin.ix().refSord(oldParentId, regId, objId, -1);
  }
});