"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.AgvNode = exports.LOCAL_VAR_ARRAY_NAME = 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 scope_setting_1 = require("../../scope-setting");
const agv_constant_1 = require("../../entity/agv.constant");
const translation_util_1 = __importStar(require("../../utils/translation.util"));
const http_util_1 = require("../../utils/http.util");
const agvc_types_1 = require("../../agvc-types");
const webscope_service_1 = require("../../webscope-service");
const TranslationUtil = translation_util_1.default;
exports.LOCAL_VAR_ARRAY_NAME = '__VAR';
class AgvNode {
  setDataModel(dataModel) {
    this.dataModel = dataModel;
    const advancedPoint = dataModel.get(this.AdvancedPointKey, null);
    if (this.isString(advancedPoint)) {
      this.advancedPoint = advancedPoint;
    }
    const advancedSettingCommand = dataModel.get(this.AdvancedSettingCommandKey, null);
    if (this.isBoolean(advancedSettingCommand)) {
      this.advancedSettingCommand = advancedSettingCommand;
    }
    const direction = dataModel.get(this.DirectionKey, null);
    if (this.isString(direction)) {
      this.direction = direction;
    }
    const expression = dataModel.get(this.ExpressionKey, null);
    if (this.isExpression(expression)) {
      this.expression = expression;
    }
    const moveToCommand = dataModel.get(this.MoveToCommandKey, null);
    if (this.isBoolean(moveToCommand)) {
      this.moveToCommand = moveToCommand;
    }
    const path = dataModel.get(this.PathKey, null);
    if (this.isString(path)) {
      this.path = path;
    }
    const pathSettingCommand = dataModel.get(this.PathSettingCommandKey, null);
    if (this.isBoolean(pathSettingCommand)) {
      this.pathSettingCommand = pathSettingCommand;
    }
    const programNodeIsDefined = dataModel.get(this.ProgramNodeIsDefinedKey, null);
    if (this.isBoolean(programNodeIsDefined)) {
      this.programNodeIsDefined = programNodeIsDefined;
    }
    const speed = dataModel.get(this.SpeedKey, null);
    if (this.isString(speed)) {
      this.speed = speed;
    }
    const wSpeed = dataModel.get(this.WSpeedKey, null);
    if (this.isString(wSpeed)) {
      this.wSpeed = wSpeed;
    }
    const goalEndRotate = dataModel.get(this.GoalEndRotateKey, null);
    if (this.isBoolean(goalEndRotate)) {
      this.goalEndRotate = goalEndRotate;
    }
    const enable = dataModel.get(this.enableKey, null);
    if (this.isBoolean(enable)) {
      this.enable = enable;
    }
    const forwardFlag = dataModel.get(this.forwardFlagKey, null);
    if (this.isBoolean(forwardFlag)) {
      this.forwardFlag = forwardFlag;
    }
    const maxDistance = dataModel.get(this.maxDistanceKey, null);
    if (this.isNumber(maxDistance)) {
      this.maxDistance = maxDistance;
    }
    const maxAngle = dataModel.get(this.maxAngleKey, null);
    if (this.isNumber(maxAngle)) {
      this.maxAngle = maxAngle;
    }
    const routePlanningStations = dataModel.get(this.RoutePlanningStationsKey, null);
    if (this.isString(routePlanningStations)) {
      this.routePlanningStations = routePlanningStations;
    }
  }
  setAdvancedPoint(advancedPoint) {
    this.advancedPoint = advancedPoint;
    return this;
  }
  getAdvancedPoint() {
    return this.advancedPoint;
  }
  setAdvancedSettingCommand(advancedSettingCommand) {
    this.advancedSettingCommand = advancedSettingCommand;
    return this;
  }
  getAdvancedSettingCommand() {
    return this.advancedSettingCommand;
  }
  setDirection(direction) {
    this.direction = direction;
    return this;
  }
  getDirection() {
    return this.direction;
  }
  setExpression(expression) {
    this.expression = expression;
    return this;
  }
  getExpression() {
    return this.expression;
  }
  setMoveToCommand(moveToCommand) {
    this.moveToCommand = moveToCommand;
    return this;
  }
  getMoveToCommand() {
    return this.moveToCommand;
  }
  setPath(path) {
    this.path = path;
    return this;
  }
  getPath() {
    return this.path;
  }
  setPathSettingCommand(pathSettingCommand) {
    this.pathSettingCommand = pathSettingCommand;
    return this;
  }
  getPathSettingCommand() {
    return this.pathSettingCommand;
  }
  setProgramNodeIsDefined(programNodeIsDefined) {
    this.programNodeIsDefined = programNodeIsDefined;
    return this;
  }
  getProgramNodeIsDefined() {
    return this.programNodeIsDefined;
  }
  setSpeed(speed) {
    this.speed = speed;
    return this;
  }
  getSpeed() {
    return this.speed;
  }
  setWSpeed(wSpeed) {
    this.wSpeed = wSpeed;
    return this;
  }
  getWSpeed() {
    return this.wSpeed;
  }
  setGoalEndRotate(goalEndRotate) {
    this.goalEndRotate = goalEndRotate;
    return this;
  }
  getGoalEndRotate() {
    return this.goalEndRotate;
  }
  setEnable(enable) {
    this.enable = enable;
    return this;
  }
  getEnable() {
    return this.enable;
  }
  setForwardFlag(forwardFlag) {
    this.forwardFlag = forwardFlag;
    return this;
  }
  getForwardFlag() {
    return this.forwardFlag;
  }
  setMaxDistance(maxDistance) {
    this.maxDistance = maxDistance;
    return this;
  }
  getMaxDistance() {
    return this.maxDistance;
  }
  setMaxAngle(maxAngle) {
    this.maxAngle = maxAngle;
    return this;
  }
  getMaxAngle() {
    return this.maxAngle;
  }
  setRoutePlanningStations(routePlanningStations) {
    this.routePlanningStations = routePlanningStations;
    return this;
  }
  getRoutePlanningStations() {
    return this.routePlanningStations;
  }
  getDataModel() {
    this.dataModel.set(this.AdvancedPointKey, this.advancedPoint, domain_1.XmlLabelType.STRING);
    this.dataModel.set(this.AdvancedSettingCommandKey, this.advancedSettingCommand, domain_1.XmlLabelType.BOOL);
    this.dataModel.set(this.DirectionKey, this.direction, domain_1.XmlLabelType.STRING);
    this.dataModel.set(this.ExpressionKey, this.expression, domain_1.XmlLabelType.STRING);
    this.dataModel.set(this.MoveToCommandKey, this.moveToCommand, domain_1.XmlLabelType.STRING);
    this.dataModel.set(this.PathKey, this.path, domain_1.XmlLabelType.STRING);
    this.dataModel.set(this.PathSettingCommandKey, this.pathSettingCommand, domain_1.XmlLabelType.STRING);
    this.dataModel.set(this.ProgramNodeIsDefinedKey, this.programNodeIsDefined, domain_1.XmlLabelType.BOOL);
    this.dataModel.set(this.SpeedKey, this.speed, domain_1.XmlLabelType.STRING);
    this.dataModel.set(this.WSpeedKey, this.wSpeed, domain_1.XmlLabelType.STRING);
    this.dataModel.set(this.GoalEndRotateKey, this.goalEndRotate, domain_1.XmlLabelType.BOOL);
    this.dataModel.set(this.enableKey, this.enable, domain_1.XmlLabelType.BOOL);
    this.dataModel.set(this.forwardFlagKey, this.forwardFlag, domain_1.XmlLabelType.BOOL);
    this.dataModel.set(this.maxDistanceKey, this.maxDistance, domain_1.XmlLabelType.FLOAT32);
    this.dataModel.set(this.maxAngleKey, this.maxAngle, domain_1.XmlLabelType.FLOAT32);
    this.dataModel.set(this.RoutePlanningStationsKey, this.routePlanningStations, domain_1.XmlLabelType.STRING);
    return this.dataModel;
  }
  setId(id) {
    this.id = id;
  }
  update(config) {
    var _a;
    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.AdvancedPointKey) {
        if (value === null) {
          this.setAdvancedPoint('');
          updated = true;
        } else if (this.isString(value) && value !== this.getAdvancedPoint()) {
          this.setAdvancedPoint(value);
          updated = true;
        } else if (typeof value === 'number' && String(value) !== this.getAdvancedPoint()) {
          this.setAdvancedPoint(String(value));
          updated = true;
        }
      } else if (key === this.AdvancedSettingCommandKey) {
        if (typeof value === 'boolean' && value !== this.getAdvancedSettingCommand()) {
          this.setAdvancedSettingCommand(value);
          updated = true;
        }
      } else if (key === this.DirectionKey) {
        if (this.isString(value) && value !== this.getDirection()) {
          this.setDirection(value);
          updated = true;
        }
      } else if (key === this.ExpressionKey) {
        if (value === null) {
          this.setExpression(null);
          updated = true;
        } else if (this.isExpression(value) && value !== this.getExpression()) {
          this.setExpression(value);
          updated = true;
        }
      } else if (key === this.MoveToCommandKey) {
        if (typeof value === 'boolean' && value !== this.getMoveToCommand()) {
          this.setMoveToCommand(value);
          updated = true;
        }
      } else if (key === this.PathKey) {
        if (value === null) {
          this.setPath('');
          updated = true;
        } else if (this.isString(value) && value !== this.getPath()) {
          this.setPath(value);
          updated = true;
        } else if (typeof value === 'number' && String(value) !== this.getPath()) {
          this.setPath(String(value));
          updated = true;
        }
      } else if (key === this.PathSettingCommandKey) {
        if (typeof value === 'boolean' && value !== this.getPathSettingCommand()) {
          this.setPathSettingCommand(value);
          updated = true;
        }
      } else if (key === this.ProgramNodeIsDefinedKey) {
        if (typeof value === 'boolean' && value !== this.getProgramNodeIsDefined()) {
          this.setProgramNodeIsDefined(value);
          updated = true;
        }
      } else if (key === this.SpeedKey) {
        if (this.isString(value) && value !== this.getSpeed()) {
          this.setSpeed(value);
          updated = true;
        }
      } else if (key === this.WSpeedKey) {
        if (this.isString(value) && value !== this.getWSpeed()) {
          this.setWSpeed(value);
          updated = true;
        } else if (typeof value === 'number' && String(value) !== this.getWSpeed()) {
          this.setWSpeed(String(value));
          updated = true;
        }
      } else if (key === this.GoalEndRotateKey) {
        if (typeof value === 'boolean' && value !== this.getGoalEndRotate()) {
          this.setGoalEndRotate(value);
          updated = true;
        }
      } else if (key === this.enableKey) {
        if (typeof value === 'boolean' && value !== this.getEnable()) {
          this.setEnable(value);
          updated = true;
        }
      } else if (key === this.forwardFlagKey) {
        if (typeof value === 'boolean' && value !== this.getForwardFlag()) {
          this.setForwardFlag(value);
          updated = true;
        }
      } else if (key === this.maxDistanceKey) {
        if (this.isNumber(Number(value)) && Number(value) !== this.getMaxDistance()) {
          this.setMaxDistance(Number(value));
          updated = true;
        }
      } else if (key === this.maxAngleKey) {
        if (this.isNumber(Number(value)) && Number(value) !== this.getMaxAngle()) {
          this.setMaxAngle(Number(value));
          updated = true;
        }
      } else if (key === this.RoutePlanningStationsKey) {
        if (value === null) {
          this.setRoutePlanningStations(null);
          updated = true;
        } else if (this.isString(value) && value !== ((_a = this.getRoutePlanningStations()) !== null && _a !== void 0 ? _a : '')) {
          this.setRoutePlanningStations(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;
  }
  isString(value) {
    return typeof value === 'string';
  }
  isBoolean(value) {
    return typeof value === 'boolean';
  }
  isNumber(value) {
    return Number.isFinite(value);
  }
  isExpression(value) {
    return typeof value === 'object' && value !== null && typeof value.append === 'function';
  }
  getValueFactory() {
    var _a, _b;
    return (_b = (_a = this.programModel).getValueFactory) === null || _b === void 0 ? void 0 : _b.call(_a);
  }
  getLocalVarName(name) {
    return `${exports.LOCAL_VAR_ARRAY_NAME}.${name}`;
  }
  getScriptLocalVarName(scriptWriter, name) {
    const writer = scriptWriter;
    if (typeof writer.getLocalVarName === 'function') {
      return writer.getLocalVarName(name);
    }
    return this.getLocalVarName(name);
  }
  constructor(programModel) {
    var _a, _b, _c;
    this.AdvancedPointKey = 'advanced_point';
    this.AdvancedSettingCommandKey = 'advanced_setting_command';
    this.DirectionKey = 'direction';
    this.ExpressionKey = 'expression';
    this.MoveToCommandKey = 'move_to_command';
    this.PathKey = 'path';
    this.PathSettingCommandKey = 'path_setting_command';
    this.ProgramNodeIsDefinedKey = 'program_node_is_defined';
    this.SpeedKey = 'speed';
    this.WSpeedKey = 'wspeed';
    this.GoalEndRotateKey = 'goal_end_rotate';
    this.enableKey = 'enable';
    this.forwardFlagKey = 'forward_flag';
    this.maxDistanceKey = 'max_distance';
    this.maxAngleKey = 'max_angle';
    this.RoutePlanningStationsKey = 'route_planning_stations';
    this.id = '';
    this.SpeedDefault = '0.8';
    this.WSpeedDefault = '3';
    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('AgvNodeContribution');
    this.advancedPoint = null;
    this.advancedSettingCommand = false;
    this.direction = 'forward';
    this.expression = null;
    this.moveToCommand = false;
    this.path = null;
    this.pathSettingCommand = false;
    this.programNodeIsDefined = false;
    this.speed = '0.8';
    this.wSpeed = (3 * Math.PI / 180).toString();
    this.goalEndRotate = false;
    this.enable = false;
    this.forwardFlag = true;
    this.maxDistance = 0;
    this.maxAngle = 0;
    this.routePlanningStations = null;
    this.programModel = programModel;
    this.language = (0, scope_setting_1.getCurrentLanguage)();
    this.node = this;
  }
  generateScript(scriptWriter) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
    const map = new Map();
    const stations = this.refreshStationsForProgramStart();
    this.logger.log(`打印站点信息：${JSON.stringify(stations)}`);
    if (stations.length == 0) {
      const msg = `AGV ${TranslationUtil.toAimLanguage(this.language, 'not connected')}`;
      this.generatePopupScript(scriptWriter, msg);
      return;
    }
    for (const station of stations) {
      map.set(station.name, station);
    }
    const targetName = (_a = this.getAdvancedPoint()) !== null && _a !== void 0 ? _a : '';
    const pathSetting = this.getPathSettingCommand();
    const path = (_b = this.getPath()) !== null && _b !== void 0 ? _b : '';
    const stationIds = [];
    if (pathSetting && path) {
      const stations = path.split('->');
      for (const station of stations) {
        const sta = map.get(station);
        sta ? stationIds.push(sta.id) : null;
      }
    }
    const targetStationId = (_c = map.get(targetName)) === null || _c === void 0 ? void 0 : _c.id;
    if (targetStationId && stationIds[stationIds.length - 1] !== targetStationId) {
      stationIds.push(targetStationId);
    }
    const tree_node = (_e = (_d = this.programModel) === null || _d === void 0 ? void 0 : _d.getProgramTree().getTreeNodeById(this.id)) === null || _e === void 0 ? void 0 : _e.model;
    if (!tree_node) {
      return;
    }
    const row = tree_node.lineNumber;
    const priorityFunName = `setPriority_${row}()`;
    const collisionLevelVar = this.getScriptLocalVarName(scriptWriter, 'collision_level');
    const priorityParamVar = this.getScriptLocalVarName(scriptWriter, `priorityParam_${row}`);
    const resVar = this.getScriptLocalVarName(scriptWriter, `priorityRes_${row}`);
    const releaseVar = this.getScriptLocalVarName(scriptWriter, `release_${row}`);
    const priorityVar = this.getScriptLocalVarName(scriptWriter, `priority_${row}`);
    const mapHeaderVar = this.getScriptLocalVarName(scriptWriter, `map_header_${row}`);
    const idVar = this.getScriptLocalVarName(scriptWriter, `id_${row}`);
    const headerVar = this.getScriptLocalVarName(scriptWriter, `header_${row}`);
    const targetPoseVar = this.getScriptLocalVarName(scriptWriter, `target_pose_${row}`);
    const maxVelVar = this.getScriptLocalVarName(scriptWriter, `max_vel_${row}`);
    const navInfoVar = this.getScriptLocalVarName(scriptWriter, `navInfo_${row}`);
    const navFailedCodeVar = this.getScriptLocalVarName(scriptWriter, `nav_failed_code_${row}`);
    const navFailedCodeRawVar = this.getScriptLocalVarName(scriptWriter, `nav_failed_code_raw_${row}`);
    const navFailedReasonVar = this.getScriptLocalVarName(scriptWriter, `nav_failed_reason_${row}`);
    const stationsIdVar = this.getScriptLocalVarName(scriptWriter, `stations_id_${row}`);
    const adjustParamVar = this.getScriptLocalVarName(scriptWriter, `adjust_param_${row}`);
    const paramVar = this.getScriptLocalVarName(scriptWriter, `param_${row}`);
    const changeModelParamVar = this.getScriptLocalVarName(scriptWriter, `changeModelParam_${row}`);
    const runningInfoVar = this.getScriptLocalVarName(scriptWriter, `runningInfo_${row}`);
    const changeRunningModeVar = this.getScriptLocalVarName(scriptWriter, `changeRunningMode_${row}`);
    const resultVar = this.getScriptLocalVarName(scriptWriter, `result_${row}`);
    const runningModeStatusVar = this.getScriptLocalVarName(scriptWriter, `runningModeStatus_${row}`);
    const navFailedFarReason = TranslationUtil.toAimLanguage(this.language, 'Too far from path start point, tracking stopped', translation_util_1.TranslationNamespace.AGV);
    const navFailedSecondaryAdjustReason = TranslationUtil.toAimLanguage(this.language, 'Secondary adjustment failed', translation_util_1.TranslationNamespace.AGV);
    const safetyEdgeTriggeredReason = TranslationUtil.toAimLanguage(this.language, 'Safety edge triggered (status: %1)', translation_util_1.TranslationNamespace.AGV).replace('%1', '" .. tostring(runningInfo.safety_edge_status) .. "');
    const navFailedWithCodeReason = TranslationUtil.toAimLanguage(this.language, 'Navigation failed (code: %1)', translation_util_1.TranslationNamespace.AGV).replace('%1', `" .. tostring(${navFailedCodeVar}) .. "`);
    scriptWriter.appendLine(`if ${exports.LOCAL_VAR_ARRAY_NAME} == nil then ${exports.LOCAL_VAR_ARRAY_NAME} = {} end`);
    scriptWriter.appendLine(`${collisionLevelVar} = getCollisionLevel()`);
    scriptWriter.appendLine('setCollisionLevel(0)');
    const valueFactory = this.getValueFactory();
    if (!valueFactory) {
      return;
    }
    scriptWriter.appendLine(`function ${priorityFunName}`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`${priorityParamVar} = { "web", "" }`);
    scriptWriter.appendLine(`${resVar} = agvc.AgvcInterface.setPriority(${priorityParamVar})`);
    const releasePriorityExpression = valueFactory.createExpression();
    releasePriorityExpression.append(`not ${resVar} or ${resVar} < 0`);
    scriptWriter.ifCondition(releasePriorityExpression);
    scriptWriter.appendLine(`${releaseVar} = agvc.AgvcInterface.releasePriority()`);
    scriptWriter.appendLine(`${priorityVar} = agvc.AgvcInterface.setPriority(${priorityParamVar})`);
    scriptWriter.appendLine(`textmsg("set priority result:" ..tostring(${priorityVar}))`);
    scriptWriter.appendLine(`return ${priorityVar}`);
    scriptWriter.end();
    scriptWriter.appendLine(`textmsg("set priority result:" ..tostring(${resVar}))`);
    scriptWriter.appendLine(`return ${resVar}`);
    scriptWriter.end();
    scriptWriter.lineFeed();
    scriptWriter.appendLine(`${mapHeaderVar} = agvc.AgvcInterface.getCurrentMapHeader()`);
    scriptWriter.appendLine(`textmsg("map_header:" ..json.encode(${mapHeaderVar}))`);
    scriptWriter.appendLine(`${idVar} = "${(0, uuid_1.v4)().toString()}"`);
    scriptWriter.appendLine(`${headerVar} = {`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`id = ${idVar},`);
    scriptWriter.appendLine(`name = ${mapHeaderVar}.name,`);
    scriptWriter.appendLine(`map_id = ${mapHeaderVar}.map_id,`);
    scriptWriter.appendLine(`stamp =  socket.gettime() * 1000`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`}`);
    scriptWriter.lineFeed();
    scriptWriter.appendLine(`${targetPoseVar} = {`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`x = ${(_g = (_f = map.get(targetName)) === null || _f === void 0 ? void 0 : _f.pose.x) !== null && _g !== void 0 ? _g : '""'},`);
    scriptWriter.appendLine(`y = ${(_j = (_h = map.get(targetName)) === null || _h === void 0 ? void 0 : _h.pose.y) !== null && _j !== void 0 ? _j : '""'},`);
    scriptWriter.appendLine(`yaw = ${(_l = (_k = map.get(targetName)) === null || _k === void 0 ? void 0 : _k.pose.yaw) !== null && _l !== void 0 ? _l : '""'}`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`}`);
    scriptWriter.lineFeed();
    const v = this.getSpeed() ? Number(this.getSpeed()) : Number(this.SpeedDefault);
    const w = this.getWSpeed() ? Number(this.getWSpeed()) : Number(this.WSpeedDefault);
    scriptWriter.appendLine(`${maxVelVar} = {`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`v = ${v},`);
    scriptWriter.appendLine(`w = ${w}`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`}`);
    scriptWriter.appendLine(`${navInfoVar} = agvc.AgvcInterface.getNavInfo()`);
    scriptWriter.appendLine(`${stationsIdVar} = {${stationIds.map(item => `'${item}'`).join(',')}}`);
    const stationExpression = valueFactory.createExpression();
    stationExpression.append(`${navInfoVar}.goal_station and ${navInfoVar}.goal_station.header.id ~= "" and ${stationsIdVar}[1] and ${stationsIdVar}[1] ~= ${navInfoVar}.goal_station.header.id`);
    scriptWriter.ifCondition(stationExpression);
    scriptWriter.appendLine(`table.insert(${stationsIdVar},1,${navInfoVar}.goal_station.header.id)`);
    scriptWriter.end();
    scriptWriter.lineFeed();
    scriptWriter.appendLine(`${adjustParamVar} = {`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`enable = ${this.getEnable()},`);
    scriptWriter.appendLine(`forward_flag = ${this.getForwardFlag()},`);
    scriptWriter.appendLine(`max_distance = ${this.getMaxDistance()},`);
    scriptWriter.appendLine(`max_angle = ${this.getMaxAngle()}`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`}`);
    scriptWriter.lineFeed();
    scriptWriter.appendLine(`${paramVar} = {`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`header = ${headerVar},`);
    scriptWriter.appendLine(`type = "PATH_TO_STATION",`);
    scriptWriter.appendLine(`target_pose = ${targetPoseVar},`);
    scriptWriter.appendLine(`stations_id = ${stationsIdVar},`);
    scriptWriter.appendLine(`forward_flag = ${this.getDirection() === agvc_types_1.ForwardFlagType.FORWARD},`);
    scriptWriter.appendLine(`max_vel = ${maxVelVar},`);
    scriptWriter.appendLine(`secondary_adjustment = ${adjustParamVar},`);
    scriptWriter.appendLine(`goal_end_rotate = ${this.getGoalEndRotate()}`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`}`);
    scriptWriter.lineFeed();
    scriptWriter.appendLine(`${priorityFunName}`);
    scriptWriter.lineFeed();
    scriptWriter.appendLine(`${changeModelParamVar} = { "${agvc_types_1.RunningMode.NAVIGATE}", ${headerVar} }`);
    scriptWriter.appendLine(`${runningInfoVar} = agvc.AgvcInterface.getRunningInfo()`);
    scriptWriter.appendLine(`if ${runningInfoVar} and ${runningInfoVar}.running_mode ~= "NAVIGATE" then`);
    scriptWriter.increaseIndent();
    {
      scriptWriter.appendLine(`${changeRunningModeVar} = agvc.AgvcInterface.changeRunningMode(${changeModelParamVar})`);
      scriptWriter.appendLine(`if ${changeRunningModeVar} == 10100201 then`);
      scriptWriter.increaseIndent();
      {
        scriptWriter.whileTrue();
        scriptWriter.sleep(0.3);
        scriptWriter.appendLine(`${resultVar} = agvc.AgvcInterface.getAsyncInterfaceResultStatus()`);
        scriptWriter.appendLine(`${runningModeStatusVar} = ${resultVar}.change_running_mode_status`);
        scriptWriter.appendLine(`if ${runningModeStatusVar} and ${runningModeStatusVar}.header and ${runningModeStatusVar}.header.id == ${headerVar}.id and ${runningModeStatusVar}.status == "FINISHED"  then`);
        scriptWriter.increaseIndent();
        scriptWriter.appendLine(`${changeRunningModeVar} = agvc.AgvcInterface.changeRunningMode(${changeModelParamVar})`);
        scriptWriter.appendLine(`break`);
        scriptWriter.decreaseIndent();
        scriptWriter.appendLine(`end`);
        scriptWriter.end();
        scriptWriter.appendLine(`textmsg("successfully switched navigation mode")`);
      }
      scriptWriter.decreaseIndent();
      scriptWriter.appendLine(`end`);
    }
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`end`);
    scriptWriter.lineFeed();
    scriptWriter.appendLine(`textmsg("send navigation parameters:" ..json.encode(${paramVar}))`);
    scriptWriter.appendLine(`${resultVar} = agvc.AgvcInterface.setNavGoal({ ${paramVar} })`);
    scriptWriter.appendLine(`textmsg("set navigation results:" ..json.encode(${resultVar}))`);
    const setNavGoalExpression = valueFactory.createExpression();
    setNavGoalExpression.append(`${resultVar} == 1`);
    scriptWriter.ifCondition(setNavGoalExpression);
    scriptWriter.appendLine(`${priorityFunName}`);
    scriptWriter.appendLine(`${resultVar} = agvc.AgvcInterface.setNavGoal({ ${paramVar} })`);
    scriptWriter.appendLine(`textmsg("reset navigation results:" ..json.encode(${resultVar}))`);
    scriptWriter.end();
    const safetyStatus = agv_constant_1.SingleInstance.getInstance().get(agv_constant_1.ConstantEnum.AGV_SAFETY_STATUS);
    if (!safetyStatus) {
      agv_constant_1.SingleInstance.getInstance().set(agv_constant_1.ConstantEnum.AGV_SAFETY_STATUS, true);
      const threadName = 'handler_thread_safety_status';
      scriptWriter.appendLine(`${threadName}=thread(function()`);
      scriptWriter.increaseIndent();
      scriptWriter.appendLine('local safetyEdgeStatus = nil');
      scriptWriter.appendLine('while true do');
      scriptWriter.increaseIndent();
      scriptWriter.appendLine('local runningInfo = agvc.AgvcInterface.getRunningInfo()');
      scriptWriter.appendLine('if runningInfo and runningInfo.safety_edge_status ~= 0 and runningInfo.safety_edge_status ~= safetyEdgeStatus then');
      scriptWriter.increaseIndent();
      scriptWriter.appendLine('safetyEdgeStatus = runningInfo.safety_edge_status');
      scriptWriter.appendLine(`popup(TraceLevel.INFO, "Info", "${safetyEdgeTriggeredReason}", 1101)`);
      scriptWriter.appendLine('pause()');
      scriptWriter.decreaseIndent();
      scriptWriter.appendLine('elseif runningInfo ~= nil then');
      scriptWriter.increaseIndent();
      scriptWriter.appendLine('safetyEdgeStatus = runningInfo.safety_edge_status');
      scriptWriter.decreaseIndent();
      scriptWriter.appendLine('end');
      scriptWriter.appendLine('sleep(0.2)');
      scriptWriter.appendLine('sched.cancel_point()');
      scriptWriter.decreaseIndent();
      scriptWriter.appendLine('end');
      scriptWriter.decreaseIndent();
      scriptWriter.appendLine('end, "thread_safety_status")');
      scriptWriter.appendLine(`run(${threadName})`);
    }
    scriptWriter.lineFeed();
    scriptWriter.whileTrue();
    scriptWriter.appendLine(`${navInfoVar} = agvc.AgvcInterface.getNavInfo()`);
    const sameTaskExpression = valueFactory.createExpression();
    sameTaskExpression.append(`${navInfoVar} and ${navInfoVar}.header and ${navInfoVar}.header.id == ${idVar}`);
    scriptWriter.ifCondition(sameTaskExpression);
    scriptWriter.appendLine(`if ${navInfoVar}.status == "FINISHED" then`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`textmsg("Navigation has completed.")`);
    scriptWriter.appendLine(`break`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`elseif ${navInfoVar}.status == "FAILED" then`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`textmsg("nav_failed_nav_info:" .. json.encode(${navInfoVar}))`);
    scriptWriter.appendLine(`${navFailedCodeRawVar} = ${navInfoVar}.error_code or ${navInfoVar}.errorCode or ${navInfoVar}.code or ${navInfoVar}.status_code or ${navInfoVar}.statusCode or (${navInfoVar}.header and (${navInfoVar}.header.error_code or ${navInfoVar}.header.errorCode or ${navInfoVar}.header.code or ${navInfoVar}.header.status_code or ${navInfoVar}.header.statusCode)) or (${navInfoVar}.error and (${navInfoVar}.error.code or ${navInfoVar}.error.error_code)) or (${navInfoVar}.result and (${navInfoVar}.result.code or ${navInfoVar}.result.error_code))`);
    scriptWriter.appendLine(`if ${navFailedCodeRawVar} == nil then`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`${navFailedCodeVar} = ""`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`else`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`${navFailedCodeVar} = tostring(${navFailedCodeRawVar})`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`end`);
    scriptWriter.appendLine(`${navFailedReasonVar} = "${navFailedWithCodeReason}"`);
    scriptWriter.appendLine(`if ${navFailedCodeVar} == "10610102" then`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`${navFailedReasonVar} = "${navFailedFarReason}"`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`elseif ${navFailedCodeVar} == "10220501" or ${navFailedCodeVar} == "10220502" or ${navFailedCodeVar} == "10220503" or ${navFailedCodeVar} == "10220504" then`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`${navFailedReasonVar} = "${navFailedSecondaryAdjustReason}"`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`end`);
    scriptWriter.appendLine(`textmsg("nav_failed_code:" .. tostring(${navFailedCodeVar}))`);
    scriptWriter.appendLine(`textmsg("nav_failed_reason:" .. tostring(${navFailedReasonVar}))`);
    scriptWriter.appendLine(`popup(TraceLevel.ERROR, "Error", ${navFailedReasonVar}, 1)`);
    scriptWriter.appendLine(`halt()`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`elseif ${navInfoVar}.status == "RUNNING" then`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`sleep(0.5)`);
    scriptWriter.appendLine(`textmsg("Navigation is running...")`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`elseif ${navInfoVar}.status == "PAUSED" then`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`sleep(0.5)`);
    scriptWriter.appendLine(`textmsg("Navigation is paused; waiting for resume...")`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`else`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`sleep(0.5)`);
    scriptWriter.appendLine(`textmsg("Navigation status:" ..tostring(${navInfoVar}.status))`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`end`);
    scriptWriter.elseCondition();
    scriptWriter.appendLine(`sleep(0.5)`);
    scriptWriter.appendLine(`textmsg("Waiting for current navigation task status...")`);
    scriptWriter.end();
    scriptWriter.end();
    const collisionExpression = valueFactory.createExpression();
    collisionExpression.append(`${collisionLevelVar} ~= nil and ${collisionLevelVar} > 0`);
    scriptWriter.ifCondition(collisionExpression);
    scriptWriter.appendLine(`setCollisionLevel(${collisionLevelVar})`);
    scriptWriter.end();
  }
  refreshStationsForProgramStart() {
    const cache = agv_constant_1.SingleInstance.getInstance();
    const cachedStations = cache.get(agv_constant_1.ConstantEnum.AGV_STATIONS) || [];
    const cachedMapId = cache.get(agv_constant_1.ConstantEnum.AGV_STATIONS_MAP_ID) || '';
    let stations = cachedStations;
    let fetchedMapId = '';
    try {
      const url = `http://${agv_constant_1.AGV_DEFAULT_HOST}:${agv_constant_1.AGV_STEERING_SERVER_PORT}/api/map/stations`;
      const response = (0, http_util_1.syncHttpRequest)(url, '');
      const payload = JSON.parse(response);
      stations = this.extractStations(payload);
      fetchedMapId = this.extractMapId(payload);
      if (cachedStations.length > 0 && cachedMapId && fetchedMapId && cachedMapId !== fetchedMapId) {
        this.logger.log(`Map changed, refresh station cache: ${cachedMapId} -> ${fetchedMapId}`);
      }
      cache.set(agv_constant_1.ConstantEnum.AGV_STATIONS, stations);
      if (fetchedMapId) {
        cache.set(agv_constant_1.ConstantEnum.AGV_STATIONS_MAP_ID, fetchedMapId);
      }
    } catch (error) {
      this.logger.error(`HTTP request failed：${error}`);
    }
    return stations;
  }
  extractMapId(payload) {
    const stations = this.extractStations(payload);
    for (const station of stations) {
      const mapIdFromStation = station === null || station === void 0 ? void 0 : station.mapId;
      if (typeof mapIdFromStation === 'string' && mapIdFromStation) {
        return mapIdFromStation;
      }
    }
    return '';
  }
  extractStations(payload) {
    const stations = payload === null || payload === void 0 ? void 0 : payload.data;
    return Array.isArray(stations) ? stations : [];
  }
  getTitle() {
    var _a, _b;
    const moveTo = (_a = this.getAdvancedPoint()) !== null && _a !== void 0 ? _a : '';
    const direction = this.getDirection();
    const path = (_b = this.getPath()) !== null && _b !== void 0 ? _b : '';
    let title;
    const language = (0, scope_setting_1.getCurrentLanguage)();
    if (this.getMoveToCommand()) {
      title = `${TranslationUtil.toAimLanguage(language, 'AMR Line Following:target station point %1,', translation_util_1.TranslationNamespace.AGV).replace('%1', moveTo)}${TranslationUtil.toAimLanguage(language, direction, translation_util_1.TranslationNamespace.AGV)}`;
    } else {
      title = `${TranslationUtil.toAimLanguage(language, `AMR Line Following`, translation_util_1.TranslationNamespace.AGV)}`;
    }
    return title;
  }
  hasDefined() {
    return true;
  }
  generatePopupScript(scriptWriter, msg) {
    scriptWriter.appendLine(`sched.sync_program_point()`);
    scriptWriter.appendLine('clearNamedVariable("_popup_continue_or_stop")');
    scriptWriter.appendLine(`do`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine('local _popup_t = getControlSystemTime()');
    const language = (0, scope_setting_1.getCurrentLanguage)();
    scriptWriter.appendLine(`popup(TraceLevel.ERROR, "Error", "${translation_util_1.default.toAimLanguage(language, msg, translation_util_1.TranslationNamespace.AGV)}", 1)`);
    scriptWriter.appendLine(`halt()`);
    scriptWriter.appendLine('while not variableUpdated("_popup_continue_or_stop", _popup_t)  do' + ' sync() ' + 'end');
    scriptWriter.appendLine('if not getBool("_popup_continue_or_stop", true) then halt() end');
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`end`);
  }
  getIcon(hasDefined) {
    return hasDefined ? `icon${agv_constant_1.PluginsProgramNodeId.AUBO_AGV}Complete` : `icon${agv_constant_1.PluginsProgramNodeId.AUBO_AGV}`;
  }
}
exports.AgvNode = AgvNode;
//# sourceMappingURL=agv-node.js.map