importPackage(java.awt);
importPackage(java.awt.geom);


include(Resources.id("mtrsteamloco:scripts/display_helper.js"));

let slotCfg = {
  "version": 1,
  "texSize": [500, 200],
  "slots": [
    {
      "name": "front",    
      "texArea": [0, 0, 500, 100],
      "pos": [
        [[-0.6601, 2.147, 7.370],  [-0.6601, 1.859, 7.370], [0.6515, 1.859, 7.370], [0.6515, 2.147, 7.370]]
      ],
      "offsets": [[0, 0, 0]]
    },
    {
      "name": "side",    
      "texArea": [0, 100, 500, 100],
      "pos": [
        [[1.232, 2.103, -1.250], [1.232, 1.767, -1.250], [1.232, 1.767, -2.643], [1.232, 2.103, -2.643]]
      ],
      "offsets": [[0, 0, 0]]
    }
  ]
};

var serifFont = Resources.readFont(Resources.idRelative("mtr:font/cat-arena.ttf"));
var dhBase = new DisplayHelper(slotCfg);
const bigFontScale = 83;
const smallFontScale = 60;

const sideTopFontScale = 40;
const sideBottomFontScale = 47;
const takeRussianName = true;

const goingToTheDepotStr = "Not in service";


function displCreate(ctx, state, train) {
	state.displUpdateRateLimit = new RateLimit(4.00);
  state.dh = dhBase.create();
  updateTexture(state, train);
}

function displDispose(ctx, state, train) {
  if (state.dh == undefined) return;
	state.dh.close();
}

function displRenderLogic(ctx, state, train) { 
	if (state.displUpdateRateLimit.shouldUpdate()) {
    updateTexture(state, train);
  }
}

function displRender(ctx, state, i, matrices) {
  ctx.drawCarModel(state.dh.model, i, matrices);
}

function updateTexture(state, train) {
    let graphFront = state.dh.graphics();

    drawDisplFront(graphFront, train);
    drawDisplSide(graphFront, train);
    state.dh.upload();
}

function drawDisplSide(g, train) {
  const routeX = 60;
  const routeY = 172;

  const isOnRoute = train.getThisRoutePlatforms().size() != 0;

  const routeNum = isOnRoute ? getRouteNum(train) : "";
  const isRouteNumEmpty = routeNum.length == 0;

  const topCharLimit = isRouteNumEmpty ? 24 : 18;
  const bottomCharLimit = isRouteNumEmpty ? 23 : 19;

  let strEndStation = isOnRoute ? getEndStation(train) : goingToTheDepotStr;
  let strEndParsed = convertString(strEndStation).substring(0, bottomCharLimit);

  let strNextStation = isOnRoute ? getNextStation(train) : "";
  let strNextParsed = convertString(strNextStation).substring(0, topCharLimit);
  strNextParsed = "-" + strNextParsed + "-";

  let platfCenterX = isRouteNumEmpty ? 250 : 309;

  const platTopY = 144;
  const platBottomY = 181;

  
  g.setColor(Color.BLACK);
  g.fillRect(0, 100, 500, 100);
  g.setColor(Color.GREEN);

  g.setFont(serifFont.deriveFont(1, sideTopFontScale));
  drawStringCenter(g, strNextParsed, platfCenterX, platTopY)
  g.setFont(serifFont.deriveFont(0, sideBottomFontScale));
  drawStringCenter(g, strEndParsed, platfCenterX, platBottomY)

  if (routeNum.length != 0 && routeNum.length <= 3) {
    g.setColor(Color.BLACK);
    g.fillRect(0, 100, 120, 100);
    g.setColor(Color.GREEN);
    g.setFont(serifFont.deriveFont(0, bigFontScale));
    drawStringCenter(g, routeNum, routeX, routeY);
  }
}

function drawDisplFront(g, train) {

  const isOnRoute = train.getThisRoutePlatforms().size() != 0;

  const routeX = 60;
  const routeY = 72;
  const routeNum = isOnRoute ? getRouteNum(train) : "";
  const isRouteNumEmpty = routeNum.length == 0;

  const platfCenterX = isRouteNumEmpty ? 250 : 309;
  const platfBigY = routeY;
  const platSmallTopY = 44;
  const platSmallBottomY = 81;

  // let fontMetrics = g.getFontMetrics();
  let strEndStation = isOnRoute ? getEndStation(train) : goingToTheDepotStr;
  let strEndParsed = convertString(strEndStation);

  g.setColor(Color.BLACK);
  g.fillRect(0, 0, 500, 100);
  g.setColor(Color.GREEN);



  const isTextBig = checkTypeOfText(strEndParsed, isRouteNumEmpty) 

  if (isTextBig) {
    g.setFont(serifFont.deriveFont(0, smallFontScale));
    let strings = parseTextToTwoStrings(strEndParsed, isRouteNumEmpty);
    let delta = strings[1] == "" ? 20 : 0;

    drawStringCenter(g, strings[0], platfCenterX, platSmallTopY + delta)
    drawStringCenter(g, strings[1], platfCenterX, platSmallBottomY)
  } else {
    g.setFont(serifFont.deriveFont(0, bigFontScale));
    drawStringCenter(g, strEndParsed, platfCenterX, platfBigY)
  }

  

  if (routeNum.length != 0 && routeNum.length <= 3) {
  g.setColor(Color.BLACK);
  g.fillRect(0, 0, 120, 100);
  g.setColor(Color.GREEN);
  g.setFont(serifFont.deriveFont(0, bigFontScale));
  drawStringCenter(g, routeNum, routeX, routeY);
  }
}

function parseTextToTwoStrings(string, isRouteNumEmpty) {
  const smallTextCharLimit = isRouteNumEmpty ? 18 : 14;
  const bigTextCharLimit = isRouteNumEmpty ? 13 : 10;
 

  if (string.length <= bigTextCharLimit) return ["", ""];

  if (string.length <= smallTextCharLimit) return [string, ""];

  let findSeparatorString = string;

  let arrOfSymbols = ['.', ',', '-', ' '];
  let replacementChar = ' ';

  for (let i = 0; i < arrOfSymbols.length; i++) {
    findSeparatorString = findSeparatorString.replace(arrOfSymbols[i], replacementChar);
  }

  let lastIndexOfSeparator = findSeparatorString.lastIndexOf(replacementChar, smallTextCharLimit);

  if (lastIndexOfSeparator == -1) {
    lastIndexOfSeparator = smallTextCharLimit - 1;
  }

    let firstHalf = string.substring(0, lastIndexOfSeparator + 1);
    let lastHalf = string.substring(lastIndexOfSeparator + 1);

    if (firstHalf[lastIndexOfSeparator] == '-') lastHalf = "-" + lastHalf; // add '-' if separator is '-'

    if (lastHalf.length > smallTextCharLimit) {
      lastHalf = lastHalf.substring(0, smallTextCharLimit - 2) + "..."
    }

    return [firstHalf, lastHalf]

}

function checkTypeOfText(strEndParsed, isRouteNumEmpty) {
  const bigTextCharLimit = isRouteNumEmpty ? 13 : 10;
  return strEndParsed.length > bigTextCharLimit;
}

function drawStringCenter(g, string, x, y){
  let fontMetrics = g.getFontMetrics();
  const newX = x - fontMetrics.stringWidth(string) / 2;

  g.drawString(string, newX, y)
}

function convertString(strEndStation) {
  const stringModified = strEndStation.toLowerCase().replace("ё", "е").replace("№", "n");
  return stringModified;
}

function getEndStation(train) {
  let stationList = train.getThisRoutePlatforms();
  let ret = "";
  if (stationList[0] == undefined) return ret;
  ret = stationList[0].destinationName;
  let lastIndex = stationList.size() - 1;
  let custom = stationList[0].route.platformIds[lastIndex].customDestination + "";
  if (custom != "") {
    return custom;
  }
  return ret += "";
}

function getNextStation(train) {
  let stationList = train.getThisRoutePlatforms();
  let ret = "";
  let nextIndex = train.getThisRoutePlatformsNextIndex()
  
  if (stationList[nextIndex] == undefined) return ret;

  let st = stationList[nextIndex].station; 
  if (st != null) ret = st.name;

  let custom = stationList[0].route.platformIds[nextIndex].customDestination + "";
  if (custom != "") {
    return custom;
  }
  return ret += "";
}



function clamp(num, min, max) {
  return Math.min(Math.max(num, min), max);
} 

function getRouteNum(train) {
  
  let stationList = train.getThisRoutePlatforms();
  let ret = stationList[0].route.lightRailRouteNumber + "";
  return ret;
}