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

var isBold = false;
var isBoldIskra = false;

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


// фул эмушник для первого вагона
let slotCfg = {
  "version": 1,
  "texSize": [1200, 200],
  "slots": [
    {
      "name": "front",    
      "texArea": [0, 0, 900, 200],
      "pos": [
        [[-0.7043, 2.112, 7.374],  [-0.7043, 1.879, 7.391], [0.6497, 1.879, 7.391], [0.6497, 2.112, 7.374]]
      ],
      "offsets": [[0, 0, 0]]
    }
  ]
};

let slotCfg2 = {
  "version": 1,
  "texSize": [1200, 200],
  "slots": [
    {
      "name": "front",    
      "texArea": [0, 0, 900, 200],
      "pos": [
        [[-1.286, 1.345, 0.5886],  [-1.296, 1.077, 0.5886], [-1.296, 1.077, 1.749], [-1.286, 1.345, 1.749]]
      ],
      "offsets": [[0, 0, 0]]
    }
  ]
};


// 

var serifFont = Resources.readFont(Resources.idRelative("mtr:font/okuda.ttf"));
var numFont = Resources.readFont(Resources.idRelative("mtr:font/bertadrug.ttf"));

const toDepot = "РЕЗЕРВНЫЙ"

var dhBase = new DisplayHelper(slotCfg);
var dhBase2 = new DisplayHelper(slotCfg2);



function displCreate(ctx, state, train) {

	state.pisRateLimit = new RateLimit(3);
  state.dh = dhBase.create();
  state.dh2 = dhBase2.create();

  updateEmuStrings(state, train);

  state.isOnRoute = train.getThisRoutePlatforms().size() != 0;
  state.emuStringFirst = getFirstStation(train)
  state.emuStringEnd = getEndStation(train)
  state.emuStringNum = getRouteNum(train)
  
}

function displDispose(ctx, state, train) {
	if (state.dh != null) state.dh.close();
  if (state.dh2 != null) state.dh2.close();
}


function displRender(ctx, state, train) {
	if (state.pisRateLimit.shouldUpdate()) {
    let g = state.dh.graphics();
    let g2 = state.dh2.graphics();

    updateEmuStrings(state, train);
    drawHeadEmu(state, train, g);
    drawHeadEmu(state, train, g2);
    
    state.dh.upload();
    state.dh2.upload();
  }

}

function updateEmuStrings(state, train) {

  if (train.getThisRoutePlatforms().size() != 0) {
    state.isOnRoute = true;
    state.emuStringFirst = getFirstStation(train);
    state.emuStringEnd = getEndStation(train);
    state.emuStringNum = getRouteNum(train)
  } else {
    state.isOnRoute = false
  }
}

function drawHeadEmu(state, train, g) {
  // PREPARE
  g.setComposite(AlphaComposite.Clear);
  g.fillRect(0, 0, 900, 200);
  g.setComposite(AlphaComposite.SrcOver);

  g.setColor(Color.BLACK);

  if (!state.isOnRoute){
    let centerX = 450;
    let centerY = 155;
    let bigFontScale = 80;
    g.setFont(numFont.deriveFont(0, bigFontScale));
    drawStringCenter(g, toDepot, centerX, centerY);
    return;
  }
  // NUMBER

  let num = state.emuStringNum.substring(0, 4)

  let numFontScale = num.length < 4 ? 87 : 78;
  let nX = 456;
  let nY = num.length < 4 ? 150 : 155;
  g.setFont(numFont.deriveFont(0, numFontScale));
  drawStringCenter(g, num, nX, nY);

  // START OF ROUTE
  let strStart = state.emuStringFirst
  let ifStartNameLong = checkTypeOfText(strStart)

  if (ifStartNameLong) {
    let smallFontScale = 100;
    let x = 185;
    let y = 85;
    let xDown = x;
    let yDown = 175

    g.setFont(serifFont.deriveFont(0, smallFontScale));
    let strings = parseTextToTwoStrings(strStart);
    let delta = strings[1] == "" ? 45 : 0;

    drawStringCenter(g, strings[0], x, y + delta)
    drawStringCenter(g, strings[1], xDown, yDown)
  } else {
    let bigFontScale = 160;
    let x = 185 
    let y = 145;
    g.setFont(serifFont.deriveFont(0, bigFontScale));
    drawStringCenter(g, strStart, x, y)
  }

  // END OF ROUTE
  let strEnd = state.emuStringEnd
  let ifEndNameLong = checkTypeOfText(strEnd)

  if (ifEndNameLong) {
    let smallFontScale = 100;
    let x = 900 - 185;
    let y = 85;
    let xDown = x;
    let yDown = 175

    g.setFont(serifFont.deriveFont(0, smallFontScale));
    let strings = parseTextToTwoStrings(strEnd);
    let delta = strings[1] == "" ? 45 : 0;

    drawStringCenter(g, strings[0], x, y + delta)
    drawStringCenter(g, strings[1], xDown, yDown)
  } else {
    let bigFontScale = 160;
    let x = 900 - 185 
    let y = 145;
    g.setFont(serifFont.deriveFont(0, bigFontScale));
    drawStringCenter(g, strEnd, x, y)
  }
  
}


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

  g.drawString(string, newX, y)
}

function getEndStation(train) {
  let stationList = train.getThisRoutePlatforms();
  if (stationList[0] == undefined) return ""
  let regularEndStation = stationList[0].destinationName;
  if (regularEndStation == "") regularEndStation = ""

  let lastSt = stationList.size() - 1;
  let customEndStation = stationList[lastSt].route.platformIds[lastSt].customDestination + "";
  print(regularEndStation, "d", customEndStation)
  return customEndStation == "" ? regularEndStation : customEndStation;
}

function getFirstStation(train) {
  let stationList = train.getThisRoutePlatforms();
  if (stationList[0] == undefined) return "";
  let station = stationList[0].station;
  let customFirstSt = stationList[0].route.platformIds[0].customDestination + "";

  let regularFirstSt = station == null ? "" : station.name
  return customFirstSt == "" ? regularFirstSt : customFirstSt;
}

function parseTextToTwoStrings(string) {
  string = string + "";
  const smallTextCharLimit = 12;
  const bigTextCharLimit = 7;


  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(strEndParsedJ) {
  let strEndParsed = strEndParsedJ + ""
  const bigTextCharLimit = 7;
  return strEndParsed.length > bigTextCharLimit;
}


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

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




function formatStationName(name) {
  if (name.length === 15) {
    return name;
  } else if (name.length > 15) {
    return name.substring(0, 14) + ".";
  } else {
    const dashesCount = 15 - name.length;
    const leftDashes = Math.floor(dashesCount / 2);
    const rightDashes = dashesCount - leftDashes;
    return ' '.repeat(leftDashes) + name;// + ' '.repeat(rightDashes);
  }
}