"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.ForceToBoardNode = void 0;
const tree_model_1 = __importDefault(require("tree-model"));
const aubo_logger_1 = require("@aubo/aubo_logger");
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 ForceToBoardNode {
  setAutoDockStation(autoDockStation) {
    this.autoDockStation = autoDockStation;
    return this;
  }
  getAutoDockStation() {
    return this.autoDockStation;
  }
  setMaxSpeed(maxSpeed) {
    this.maxSpeed = maxSpeed;
    return this;
  }
  getMaxSpeed() {
    return this.maxSpeed;
  }
  setDataModel(dataModel) {
    this.dataModel = dataModel;
    const autoDockStation = dataModel.get(this.AutoDockStationKey, null);
    if (this.isString(autoDockStation)) {
      this.autoDockStation = autoDockStation;
    }
    const maxSpeed = dataModel.get(this.MaxSpeedKey, null);
    if (this.isNumber(maxSpeed)) {
      this.maxSpeed = maxSpeed;
    }
  }
  getDataModel() {
    const model = this.dataModel;
    model.set(this.AutoDockStationKey, this.autoDockStation, domain_1.XmlLabelType.STRING);
    model.set(this.MaxSpeedKey, this.maxSpeed, domain_1.XmlLabelType.FLOAT32);
    return model;
  }
  isString(value) {
    return typeof value === 'string';
  }
  isNumber(value) {
    return Number.isFinite(value);
  }
  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) {
    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.AutoDockStationKey) {
        if (value === null) {
          if (this.getAutoDockStation() !== null) {
            this.setAutoDockStation(null);
            updated = true;
          }
        } else if (this.isString(value) && value !== ((_a = this.getAutoDockStation()) !== null && _a !== void 0 ? _a : '')) {
          this.setAutoDockStation(value);
          updated = true;
        }
      } else if (key === this.MaxSpeedKey) {
        if (this.isNumber(Number(value)) && Number(value) !== this.getMaxSpeed()) {
          this.setMaxSpeed(Number(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 nodeData = node.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.AutoDockStationKey = 'auto_dock_station';
    this.MaxSpeedKey = 'max_speed';
    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('ForceToBoardNodeContribution');
    this.autoDockStation = null;
    this.maxSpeed = 0.8;
    this.programModel = programModel;
  }
  generateScript(scriptWriter) {
    var _a, _b, _c, _d, _e;
    const map = new Map();
    const treeNode = (_b = (_a = this.programModel) === null || _a === void 0 ? void 0 : _a.getProgramTree().getTreeNodeById(this.id)) === null || _b === void 0 ? void 0 : _b.model;
    if (!treeNode) {
      return;
    }
    const row = treeNode.lineNumber;
    if (this.getAutoDockStation()) {
      const stations = agv_constant_1.SingleInstance.getInstance().get(agv_constant_1.ConstantEnum.AGV_STATIONS);
      this.logger.log(`打印站点信息：${JSON.stringify(stations)}`);
      if (!stations || stations.length === 0) return;
      for (const station of stations) {
        map.set(station.name, station);
      }
    }
    const valueFactory = this.getValueFactory();
    if (!valueFactory) {
      return;
    }
    const headerFunName = `getHeader_${row}()`;
    const priorityFunName = `setPriority_${row}()`;
    scriptWriter.appendLine('local collision_level = getCollisionLevel()');
    scriptWriter.appendLine('setCollisionLevel(0)');
    scriptWriter.appendLine(`function ${headerFunName}`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine('local map_header = agvc.AgvcInterface.getCurrentMapHeader()');
    scriptWriter.appendLine('local header = {');
    scriptWriter.increaseIndent();
    scriptWriter.appendLine('id = tostring(socket.gettime() * 1000),');
    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('local maxSpeed = {');
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`v = ${this.getMaxSpeed()},`);
    scriptWriter.appendLine('w = 0');
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine('}');
    scriptWriter.lineFeed();
    const autoDockStation = (_c = this.getAutoDockStation()) !== null && _c !== void 0 ? _c : '';
    scriptWriter.appendLine('local auto_charging_param = {');
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`header = ${headerFunName},`);
    scriptWriter.appendLine('auto_charging_type = "FORCE_TO_BOARD",');
    scriptWriter.appendLine(`cp_station_id = "${(_e = (_d = map.get(autoDockStation)) === null || _d === void 0 ? void 0 : _d.id) !== null && _e !== void 0 ? _e : ''}",`);
    scriptWriter.appendLine(`leave_to_station_id =  '' ,`);
    scriptWriter.appendLine('max_speed = maxSpeed');
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine('}');
    scriptWriter.lineFeed();
    scriptWriter.appendLine(`${priorityFunName}`);
    scriptWriter.appendLine('local charging_result = agvc.AgvcInterface.sendAutoChargingCommand({ auto_charging_param })');
    scriptWriter.appendLine('textmsg("forced agv to charging board result: " ..tostring(charging_result))');
    scriptWriter.whileTrue();
    scriptWriter.appendLine('local navInfo = agvc.AgvcInterface.getNavInfo()');
    const navInfoExpression = valueFactory.createExpression();
    navInfoExpression.append('navInfo and navInfo.header and navInfo.header.id == auto_charging_param.header.id and navInfo.status == "FINISHED"');
    scriptWriter.ifCondition(navInfoExpression);
    scriptWriter.appendLine('textmsg("force agv to charging board successfully.")');
    scriptWriter.appendLine('break');
    scriptWriter.elseCondition();
    scriptWriter.sleep(0.5);
    scriptWriter.appendLine('textmsg("forcing agv to charging board.")');
    scriptWriter.end();
    scriptWriter.end();
    const collisionExpression = valueFactory.createExpression();
    collisionExpression.append('collision_level ~= nil and collision_level > 0');
    scriptWriter.ifCondition(collisionExpression);
    scriptWriter.appendLine('setCollisionLevel(collision_level)');
    scriptWriter.end();
  }
  hasDefined() {
    return true;
  }
  getTitle() {
    var _a;
    const language = (0, scope_setting_1.getCurrentLanguage)();
    const stationName = ((_a = this.getAutoDockStation()) !== null && _a !== void 0 ? _a : '').trim() || TranslationUtil.toAimLanguage(language, 'Not Set', translation_util_1.TranslationNamespace.AGV);
    return `${TranslationUtil.toAimLanguage(language, 'Force to board:', translation_util_1.TranslationNamespace.AGV)} ${stationName}`;
  }
  getIcon(hasDefined) {
    return hasDefined ? `icon${agv_constant_1.PluginsProgramNodeId.AUBO_FORCE_TO_BOARD}Complete` : `icon${agv_constant_1.PluginsProgramNodeId.AUBO_FORCE_TO_BOARD}`;
  }
}
exports.ForceToBoardNode = ForceToBoardNode;
//# sourceMappingURL=force-to-board-node.js.map