include(Resources.id("mtrsteamloco:scripts/display_helper.js"));
importPackage(java.awt);
importPackage(java.awt.geom);
importPackage(java.io);
importPackage(java.net);
importPackage(java.util);
importPackage(java.lang);
importPackage(java.util.concurrent);

const top_text = new ConfigResponder.TextField("top_text", ComponentUtil.translatable("上部テキスト"), "4ッドア乗車口");
const top_color = new ConfigResponder.TextField("top_color", ComponentUtil.translatable("上部色"), "56,135,67");
const bottom_text = new ConfigResponder.TextField("bottom_text", ComponentUtil.translatable("下部テキスト"), "1");
const bottom_color = new ConfigResponder.TextField("bottom_color", ComponentUtil.translatable("下部色"), "56,135,67");

let slotCfg = {
  "version": 1,
  "texSize": [100, 50],
  "slots": [{
    "name": "main",
    "texArea": [0, 0, 100, 50],
    "pos": [[[-0.375, 2.86875, 0], [-0.375, 2.49375, 0], [0.375, 2.49375, 0], [0.375, 2.86875, 0]]],
    "offsets": [[0, 0, 0.01]]
  }]
};
let dhBase = new DisplayHelper(slotCfg);
let activeLCDs = [];
let asyncPool = null;

function create(ctx, state, entity) {
  state.dh = dhBase.create();
  state.displayRate = new RateLimit(2.0);
  state.font = Resources.readFont(Resources.id("mtrsteamloco:eyecandies/font/notosansjp/notosansjp.ttf"));


  activeLCDs.push({ ctx: ctx, state: state, entity: entity });

  if (Resources.ANTE_FLAG && asyncPool === null) {
    asyncPool = Executors.newScheduledThreadPool(1);
    asyncPool.scheduleAtFixedRate(new java.lang.Runnable({
      run: () => {
        for (let i = 0; i < activeLCDs.length; i++) {
          let entry = activeLCDs[i];
          if (!entry.state.dh || entry.state.dh.closed) continue;

          try {
            tick(entry.ctx, entry.state, entry.entity);
            entry.ctx.drawCalls.put(
              i,
              new ClusterDrawCall(entry.state.dh.model, new Matrix4f())
            );
          } catch (e) {
          }
        }
      }
    }), 0, 1000 / 0.5, TimeUnit.MILLISECONDS);
  }
}

function dispose(ctx, state, entity) {
  for (let i = activeLCDs.length - 1; i >= 0; i--) {
    if (activeLCDs[i].entity.equals(entity)) {
      activeLCDs.splice(i, 1);
      break;
    }
  }

  if (activeLCDs.length === 0 && asyncPool !== null) {
    asyncPool.shutdown();
    asyncPool = null;
  }
  state.dh.close();
}

function render(ctx, state, entity) {
  entity.registerCustomConfig(top_text);
  entity.registerCustomConfig(top_color);
  entity.registerCustomConfig(bottom_text);
  entity.registerCustomConfig(bottom_color);

  if (!Resources.ANTE_FLAG) {
    tick(ctx, state, entity);
    ctx.drawModel(state.dh.model, null);
  }
}

function stringToColor(colorStr) {
    if (!colorStr) return new Color(0.0, 0.0, 0.0);
    
    let parts = colorStr.split(",");
    if (parts.length !== 3) return new Color(0.0, 0.0, 0.0);

    return new Color(
        parseFloat(parts[0].trim()) / 255,
        parseFloat(parts[1].trim()) / 255,
        parseFloat(parts[2].trim()) / 255
    );
}

function tick(ctx, state, entity) {
  let topText = entity.getCustomConfig("top_text");
  let topColor = stringToColor(entity.getCustomConfig("top_color"));
  let bottomText = entity.getCustomConfig("bottom_text");
  let bottomColor = stringToColor(entity.getCustomConfig("bottom_color"));

  let g;
  g = state.dh.graphicsFor("main");

  g.setComposite(AlphaComposite.Clear);
  g.fillRect(0, 0, 100, 50);
  g.setComposite(AlphaComposite.SrcOver);

  //top
  g.setColor(topColor);
  g.fillRect(10, 5, 80, 15);
  assyukuDraw(g, topText, 15, 18, 80, state.font, Color.white, 10);

  //bottom
  g.setColor(bottomColor);
  g.fillOval(37.5, 22.5, 25, 25);
  assyukuDraw(g, bottomText, 20, 43, 20, state.font, Color.white, 40);

  state.dh.upload();
}

function assyukuDraw(g, text, textSize, drawPos, targetWidth, font, textColor, offsetX) {
  let fm = g.getFontMetrics(font.deriveFont(Font.PLAIN, textSize));

  if (fm.stringWidth(text) > targetWidth) {
    let nextStaScale = targetWidth / fm.stringWidth(text);
    // ★スケール適用フォント
    g.setFont(font.deriveFont(AffineTransform.getScaleInstance(nextStaScale, 1.0)).deriveFont(Font.PLAIN, textSize));
    // ★スケール後の実際の幅で中央揃え！
    let scaledWidth = fm.stringWidth(text) * nextStaScale;
    let startX = offsetX + ((targetWidth - scaledWidth) / 2);
    g.setColor(textColor);
    g.drawString(text, startX, drawPos);
  } else {
    // ★スケール不要時も中央揃え
    g.setFont(font.deriveFont(Font.PLAIN, textSize));
    g.setColor(textColor);
    let currentWidth = fm.stringWidth(text);
    let startX = offsetX + ((targetWidth - currentWidth) / 2);
    g.drawString(text, startX, drawPos);
  }
}

function assyukuDrawNotCenter(g, text, textSize, drawPos, targetWidth, font, textColor, offsetX) {
  let originalFont = font.deriveFont(Font.PLAIN, textSize);
  let fm = g.getFontMetrics(originalFont);


  if (fm.stringWidth(text) > targetWidth) {
    let scale = targetWidth / fm.stringWidth(text);
    let scaledFont = font.deriveFont(AffineTransform.getScaleInstance(scale, 1.0))
      .deriveFont(Font.PLAIN, textSize);
    g.setFont(scaledFont);
    g.setFont(scaledFont);  // ★2回セット
    g.setColor(textColor);
    g.drawString(text, offsetX, drawPos);
  } else {
    g.setFont(originalFont);
    g.setColor(textColor);
    g.drawString(text, offsetX, drawPos);
  }
}

function use(ctx, state, entity, player) {

}