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.5958, 1.892, 5.778],  [-0.5958, 1.654, 5.778], [0.6072, 1.654, 5.778], [0.6072, 1.892, 5.778]]
      ],
      "offsets": [[0, 0, 0]]
    },
    {
      "name": "side",    
      "texArea": [0, 0, 900, 200],
      "pos": [
        [[-1.225, 0.9372, -2.956], [-1.231, 0.6961, -2.956], [-1.231, 0.6961, -1.920], [-1.225, 0.9372, -1.920]]
      ],
      "offsets": [[0, 0, 0]]
    },
    {
      "name": "back",    
      "texArea": [900, 0, 300, 200],
      "pos": [
        [[0.1439, 1.9, -5.760], [0.1439, 1.76, -5.760], [-0.1405, 1.76, -5.760], [-0.1405, 1.9, -5.760]]
      ],
      "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);



function displCreate(ctx, state, train) {

	state.pisRateLimit = new RateLimit(3);
  state.dh = dhBase.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();
}


function displRender(ctx, state, train) {
	if (state.pisRateLimit.shouldUpdate()) {
    updateEmuStrings(state, train);
    drawHeadEmu(state, train)
    state.dh.upload();
  }

  ctx.drawCarModel(state.dh.model, 0, null);
}

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) {
  let g = state.dh.graphics();

  // PREPARE
  g.setComposite(AlphaComposite.Clear);
  g.fillRect(0, 0, 1200, 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)
  }
  // END

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

    let numFontScale = 110;
    let nX = 1050;
    let nY = 175;
    g.setFont(numFont.deriveFont(0, numFontScale));
    drawStringCenter(g, num, nX, nY);
  }
  
}


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 + "";

  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 <= 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(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 shortenString(str) { // unused here 
    const replacements = {
        "площадь": "пл.",
        "улица": "ул.",
        "проспект": "пр.",
        "бульвар": "б-р.",
        "шоссе": "ш.",
        "переулок": "пер.",
        "набережная": "наб.",
        "проезд": "пр-д",
        "тупик": "туп.",
        "вокзал": "вкз.",
        "аллея": "ал.",
        "тракт": "тр.",
        "микрорайон": "мкр.",
        "квартал": "кв.",
        "район": "р-н.",
        "город": "г.",
        "село": "с.",
        "посёлок": "пос.",
        "поселок": "пос.",
        "жилой комплекс": "жк.",
        "школа": "шк.",
        "станция метро": "м.",
        "метро": "м.",
        "станция": "ст.",
        "имени": "им.",
        "институт": "инст.",
        "Площадь": "Пл.",
        "Улица": "Ул.",
        "Проспект": "Пр.",
        "Бульвар": "Б-р.",
        "Шоссе": "Ш.",
        "Переулок": "Пер.",
        "Набережная": "Наб.",
        "Проезд": "Пр-д",
        "Тупик": "Туп.",
        "Вокзал": "Вкз.",
        "Аллея": "Ал.",
        "Тракт": "Тр.",
        "Микрорайон": "Мкр.",
        "Квартал": "Кв.",
        "Район": "Р-н.",
        "Город": "г.",
        "Село": "с.",
        "Посёлок": "Пос.",
        "Поселок": "Пос.",
        "Жилой комплекс": "ЖК.",
        "Школа": "Шк.",
        "Станция метро": "м.",
        "Метро": "м.",
        "Станция": "ст.",
        "Имени": "им.",
        "Институт": "Инст."
    };

    let shortenedStr = str;

    for (let key in replacements) {
        shortenedStr = (shortenedStr + "").replace(new RegExp(`${key}\\s`, 'g'), replacements[key]);
    }

    shortenedStr = shortenedStr.replace(/"/g, '');
    shortenedStr = shortenedStr.replace(/'/g, '"');

    return shortenedStr;
}



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);
  }
}