"use strict";

var __createBinding = void 0 && (void 0).__createBinding || (Object.create ? function (o, m, k, k2) {
  if (k2 === undefined) k2 = k;
  var desc = Object.getOwnPropertyDescriptor(m, k);
  if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
    desc = {
      enumerable: true,
      get: function () {
        return m[k];
      }
    };
  }
  Object.defineProperty(o, k2, desc);
} : function (o, m, k, k2) {
  if (k2 === undefined) k2 = k;
  o[k2] = m[k];
});
var __setModuleDefault = void 0 && (void 0).__setModuleDefault || (Object.create ? function (o, v) {
  Object.defineProperty(o, "default", {
    enumerable: true,
    value: v
  });
} : function (o, v) {
  o["default"] = v;
});
var __importStar = void 0 && (void 0).__importStar || function () {
  var ownKeys = function (o) {
    ownKeys = Object.getOwnPropertyNames || function (o) {
      var ar = [];
      for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
      return ar;
    };
    return ownKeys(o);
  };
  return function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
    __setModuleDefault(result, mod);
    return result;
  };
}();
var __importDefault = void 0 && (void 0).__importDefault || function (mod) {
  return mod && mod.__esModule ? mod : {
    "default": mod
  };
};
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.AlignRailwayNode = void 0;
const tree_model_1 = __importDefault(require("tree-model"));
const aubo_logger_1 = require("@aubo/aubo_logger");
const uuid_1 = require("uuid");
const domain_1 = require("../../domain");
const agv_constant_1 = require("../../entity/agv.constant");
const translation_util_1 = __importStar(require("../../utils/translation.util"));
const scope_setting_1 = require("../../scope-setting");
const webscope_service_1 = require("../../webscope-service");
const TranslationUtil = translation_util_1.default;
class AlignRailwayNode {
  setAlignRailway(v) {
    this.alignRailway = v;
    return this;
  }
  getAlignRailway() {
    return this.alignRailway;
  }
  setDataModel(dataModel) {
    this.dataModel = dataModel;
    const alignRailway = dataModel.get(this.AlignRailwayKey, null);
    if (this.isBoolean(alignRailway)) {
      this.alignRailway = alignRailway;
    }
  }
  getDataModel() {
    this.dataModel.set(this.AlignRailwayKey, this.alignRailway, domain_1.XmlLabelType.BOOL);
    return this.dataModel;
  }
  isBoolean(value) {
    return typeof value === 'boolean';
  }
  getValueFactory() {
    var _a, _b;
    return (_b = (_a = this.programModel).getValueFactory) === null || _b === void 0 ? void 0 : _b.call(_a);
  }
  setId(id) {
    this.id = id;
  }
  update(config) {
    let updated = false;
    for (const key in config) {
      const raw = config[key];
      const value = raw && typeof raw === 'object' && 'value' in raw ? raw.value : raw;
      if (key === this.AlignRailwayKey && typeof value === 'boolean' && value !== this.getAlignRailway()) {
        this.setAlignRailway(value);
        updated = true;
      }
    }
    return updated;
  }
  dropNode() {}
  toJSON() {
    const result = {};
    const model = this.getDataModel();
    if (!model || typeof model.getKeys !== 'function') {
      return result;
    }
    model.getKeys().forEach(key => {
      result[key] = {
        value: model.get(key, null),
        hasDefined: !!model.get(key, null)
      };
    });
    return result;
  }
  cloneNode(node) {
    const treeModelInstance = new tree_model_1.default();
    const parseTree = treeModelInstance.parse({});
    const {
      children,
      programNode,
      ...restData
    } = node;
    const nodeData = programNode.getDataModel();
    this.setDataModel(nodeData);
    const currentNode = this.programModel.getProgramTree().addChild(parseTree, node.nodeId, this, 0);
    currentNode.model.disabled = node.disabled;
    currentNode.model.isBreakpoint = node.isBreakpoint;
    currentNode.model.suppressedComment = node.suppressedComment;
    return currentNode;
  }
  constructor(programModel) {
    var _a, _b, _c;
    this.AlignRailwayKey = 'align_railway';
    this.id = '';
    this.logger = (_c = (_b = (_a = (0, webscope_service_1.getWebscopeService)()) === null || _a === void 0 ? void 0 : _a.getLogger) === null || _b === void 0 ? void 0 : _b.call(_a)) !== null && _c !== void 0 ? _c : new aubo_logger_1.AsLogger('AlignRailwayNodeContribution');
    this.alignRailway = true;
    this.programModel = programModel;
    this.node = this;
  }
  generateScript(scriptWriter) {
    var _a, _b, _c, _d;
    const tree_node = (_b = (_a = this.programModel) === null || _a === void 0 ? void 0 : _a.getProgramTree().getTreeNodeById(this.id)) === null || _b === void 0 ? void 0 : _b.model;
    if (!tree_node) {
      return;
    }
    const row = tree_node.lineNumber;
    const valueFactory = (_d = (_c = (0, webscope_service_1.getWebscopeService)()) === null || _c === void 0 ? void 0 : _c.getValueFactory) === null || _d === void 0 ? void 0 : _d.call(_c);
    if (!valueFactory) {
      return;
    }
    const headerFunName = `getHeader_${row}()`;
    const priorityFunName = `setPriority_${row}()`;
    const language = (0, scope_setting_1.getCurrentLanguage)();
    scriptWriter.appendLine(`function ${headerFunName}`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`local map_header = agvc.AgvcInterface.getCurrentMapHeader()`);
    scriptWriter.appendLine(`local id = "${(0, uuid_1.v4)().toString()}"`);
    scriptWriter.appendLine(`local header = {`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`id = id,`);
    scriptWriter.appendLine(`name = map_header.name,`);
    scriptWriter.appendLine(`map_id = map_header.map_id,`);
    scriptWriter.appendLine(`stamp =  socket.gettime() * 1000`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`}`);
    scriptWriter.appendLine(`return header`);
    scriptWriter.end();
    scriptWriter.lineFeed();
    scriptWriter.appendLine(`function ${priorityFunName}`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`local priorityParam = { "web", "" }`);
    scriptWriter.appendLine(`local res = agvc.AgvcInterface.setPriority(priorityParam)`);
    const releasePriorityExpression = valueFactory.createExpression();
    releasePriorityExpression.append(`not res or res < 0`);
    scriptWriter.ifCondition(releasePriorityExpression);
    scriptWriter.appendLine(`local release = agvc.AgvcInterface.releasePriority()`);
    scriptWriter.appendLine(`local priority = agvc.AgvcInterface.setPriority(priorityParam)`);
    scriptWriter.appendLine(`textmsg("set priority result:" ..tostring(priority))`);
    scriptWriter.appendLine(`return priority`);
    scriptWriter.end();
    scriptWriter.appendLine(`textmsg("set priority result:" ..tostring(res))`);
    scriptWriter.appendLine(`return res`);
    scriptWriter.end();
    scriptWriter.lineFeed();
    scriptWriter.appendLine(`${priorityFunName}`);
    scriptWriter.appendLine(`local header = ${headerFunName}`);
    scriptWriter.appendLine(`local async_status = agvc.AgvcInterface.getAsyncInterfaceResultStatus()`);
    const asyncAlignHeaderIdNotEmptyExpression = valueFactory.createExpression();
    asyncAlignHeaderIdNotEmptyExpression.append(`async_status and async_status.align_railway_status and async_status.align_railway_status.header and async_status.align_railway_status.header.id and tostring(async_status.align_railway_status.header.id) ~= ""`);
    scriptWriter.ifCondition(asyncAlignHeaderIdNotEmptyExpression);
    scriptWriter.appendLine(`agvc.AgvcInterface.autoAlignRailway({command_header = header})`);
    scriptWriter.end();
    scriptWriter.appendLine(`local align_result = agvc.AgvcInterface.autoAlignRailway({command_header = header})`);
    scriptWriter.appendLine(`while align_result == 10100201 do`);
    scriptWriter.appendLine(`  ${priorityFunName}`);
    scriptWriter.appendLine(`  align_result = agvc.AgvcInterface.autoAlignRailway({command_header = header})`);
    scriptWriter.appendLine(`  textmsg("autoAlignRailway retry result: " .. tostring(align_result))`);
    scriptWriter.appendLine(`  sleep(0.3)`);
    scriptWriter.appendLine(`end`);
    scriptWriter.appendLine(`textmsg("autoAlignRailway call result: " .. tostring(align_result))`);
    scriptWriter.appendLine(`local level = 0`);
    scriptWriter.appendLine(`if not align_result then`);
    scriptWriter.appendLine(`  level = 9`);
    scriptWriter.appendLine(`else`);
    scriptWriter.appendLine(`  level = math.floor(align_result / 10000) % 10`);
    scriptWriter.appendLine(`end`);
    const alignFailedExpression = valueFactory.createExpression();
    alignFailedExpression.append(`level ~= 0`);
    scriptWriter.ifCondition(alignFailedExpression);
    scriptWriter.appendLine(`agvc.AgvcInterface.releasePriority()`);
    const errorMsg = translation_util_1.default.toAimLanguage(language, 'autoAlignRailway failed', translation_util_1.TranslationNamespace.AGV);
    scriptWriter.appendLine(`popup(TraceLevel.ERROR, "Error", "${errorMsg}: " .. tostring(align_result) .. ", level=" .. tostring(level), 1)`);
    scriptWriter.appendLine(`halt()`);
    scriptWriter.end();
    scriptWriter.lineFeed();
  }
  hasDefined() {
    return true;
  }
  getTitle() {
    const language = (0, scope_setting_1.getCurrentLanguage)();
    return translation_util_1.default.toAimLanguage(language, 'Track Alignment', translation_util_1.TranslationNamespace.AGV);
  }
  getIcon(hasDefined) {
    return hasDefined ? `icon${agv_constant_1.PluginsProgramNodeId.AUBO_ALIGN_RAILWAY}Complete` : `icon${agv_constant_1.PluginsProgramNodeId.AUBO_ALIGN_RAILWAY}`;
  }
}
exports.AlignRailwayNode = AlignRailwayNode;
//# sourceMappingURL=alignrailway-node.js.map