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

var isBold = true;

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

// фул эмушник для первого вагона
let slotCfg = {
  "version": 1,
  "texSize": [1400, 200],
  "slots": [
    {
      "name": "front",    
      "texArea": [0, 0, 1400, 200],
      "pos": [
        [[-0.7266, 1.964, 6.226],  [-0.7266, 1.757, 6.226], [0.7478, 1.757, 6.226], [0.7478, 1.964, 6.226]]
      ],
      "offsets": [[0, 0, 0]]
    },
    {
      "name": "side",    
      "texArea": [0, 0, 1400, 200],
      "pos": [
        [[-1.169, 1.670, -1.278], [-1.169, 1.505, -1.278], [-1.169, 1.505, -0.1547], [-1.169, 1.670, -0.1547]]
      ],
      "offsets": [[0, 0, 0]]
    }
  ]
};
// эмушник для второго вагона (сиферки)

let slotCfg2 = {
  "version": 1,
  "texSize": [400, 200],
  "slots": [
    {
      "name": "back",    
      "texArea": [0, 0, 400, 200],
      "pos": [
        [[-0.5931, 1.62, -2.994],  [-0.5931, 1.475, -2.994], [-0.9305, 1.475, -2.994], [-0.9305, 1.62, -2.994]]
      ],
      "offsets": [[0, 0, 0]]
    }
  ]
};

// 

var serifFont = Resources.readFont(Resources.idRelative("mtr:font/iskra.ttf"));
const toDepot = "в парк"
const toDepot2 = "посадки нет"

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

const literX = 305;
const literY = 165;

const numX = 30;
const numY = 170; 

function displCreate(ctx, state, train) {

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

  updateEmuStrings(state, train) 
  
}

function displDispose(ctx, state, train) {
	state.dh.close();
}
function displRender(ctx, state, train, matrices) {
	if (state.pisRateLimit.shouldUpdate()) {
    updateEmuStrings(state, train);
    drawHeadEmu(state, train)
    drawTailEmu(state, train)
    state.dh.upload();
    state.dh2.upload();
  }

  ctx.drawCarModel(state.dh.model, 1, null);
  ctx.drawCarModel(state.dh2.model, 3, null);
}

function updateEmuStrings(state, train) {
  if (train.getThisRoutePlatforms().size() != 0) {
    state.emuStringFirst = getFirstStation(train);
    state.emuStringEnd = getEndStation(train);
    state.emuStringNum = splitNum(getRouteNum(train))
  } else {
    state.emuStringFirst = toDepot;
    state.emuStringEnd = toDepot2;
    state.emuStringNum = ["---", ""]
  }
}

function drawHeadEmu(state, train) {
  const x = 455;
  const yUp = 83;
  const yDown = 184;

  const xDelta = 63;
  const digitDelta = 7;
  const symbolDelta = 13;

  let g = state.dh.graphics();

  g.setComposite(AlphaComposite.Clear);
  g.fillRect(0, 0, 1400, 200);
  g.setComposite(AlphaComposite.SrcOver);

  g.setColor(new Color(1, 0.5, 0));
  g.setFont(serifFont.deriveFont(isBold * 1, 78));

  // UPPER TEXT
  let upperText = formatStationName(shortenString(state.emuStringFirst));

  for (var i = 0; i < upperText.length; i++) {
    if (upperText[i] == ' ') continue;

    let yDelta = !isNaN(upperText[i]) ? digitDelta : 0.0; // if char is number then опустить
    yDelta = upperText[i] == '\'' || upperText[i] == '\"' ? symbolDelta : 0.0;

    g.drawString(upperText[i], x + xDelta * i, yUp + yDelta);
  }

  // DOWN TEXT
  let downText = formatStationName(shortenString(state.emuStringEnd));

  for (var i = 0; i < downText.length; i++) {
    if (downText[i] == ' ') continue;

    let yDelta = !isNaN(downText[i]) ? digitDelta : 0.0; // if char is number then опустить
    yDelta = downText[i] == '\'' || downText[i] == '\"' ? symbolDelta : 0.0;

    g.drawString(downText[i], x + xDelta * i, yDown + yDelta);
  }

  // NUMBER CHAR
  g.drawString(state.emuStringNum[1], literX, literY);

  // NUMBER OF ROUTE
  g.setFont(serifFont.deriveFont(isBold * 1, 130));

  let numOfNums = state.emuStringNum[0].length;
  for (let i = 0; i < numOfNums; i++) {
    g.drawString(state.emuStringNum[0][i], numX + 93 * (3 - numOfNums) + 93 * i, numY);
  }

  /*g.drawString(state.emuStringNum[0][0], numX, numY);
  g.drawString(state.emuStringNum[0][1], numX + 93 , numY);
  g.drawString(state.emuStringNum[0][2], numX + 93 * 2, numY);*/
}

function drawTailEmu(state, train) {
  const x = 455;
  const yUp = 83;
  const yDown = 184;

  const xDelta = 63;
  const digitDelta = 7;
  const symbolDelta = 13;

  let g = state.dh2.graphics();

  g.setComposite(AlphaComposite.Clear);
  g.fillRect(0, 0, 1400, 200);
  g.setComposite(AlphaComposite.SrcOver);

  g.setColor(new Color(1, 0.5, 0));
  g.setFont(serifFont.deriveFont(isBold * 1, 78));

  // NUMBER CHAR
  g.drawString(state.emuStringNum[1], literX, literY);

  // NUMBER OF ROUTE
  g.setFont(serifFont.deriveFont(isBold * 1, 130));

  let numOfNums = state.emuStringNum[0].length;
  for (let i = 0; i < numOfNums; i++) {
    g.drawString(state.emuStringNum[0][i], numX + 93 * (3 - numOfNums) + 93 * i, numY);
  }
}

function getEndStation(train) {
  let stationList = train.getThisRoutePlatforms();
  let ret = "";
  ret = stationList[0].destinationName;
  return ret;
}

function getFirstStation(train) {
  let stationList = train.getThisRoutePlatforms();
  let station = stationList[0].station;
  
  let ret = station == null ? "ошибка эму" : station.name;
  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;
}

function shortenString(str) {
    const replacements = {
        "площадь": "пл.",
        "улица": "ул.",
        "проспект": "пр.",
        "бульвар": "б-р.",
        "шоссе": "ш.",
        "переулок": "пер.",
        "набережная": "наб.",
        "проезд": "пр-д",
        "тупик": "туп.",
        "вокзал": "вкз.",
        "аллея": "ал.",
        "тракт": "тр.",
        "микрорайон": "мкр.",
        "квартал": "кв.",
        "район": "р-н.",
        "город": "г.",
        "село": "с.",
        "посёлок": "пос.",
        "поселок": "пос.",
        "жилой комплекс": "жк.",
        "школа": "шк.",
        "станция метро": "м.",
        "метро": "м.",
        "станция": "ст.",
        "имени": "им.",
        "институт": "инст."
    };

    let shortenedStr = str.toLowerCase();

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

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

    return shortenedStr;
}

function splitNum(str) {
  if (str == "") return ["   ", " "];
    let numbers = '';
    let letters = '';

    for (let i = 0; i < str.length; i++) {
        if (!isNaN(str[i])) {
            numbers += str[i];
        } else {
            letters += str[i];
        }
    }

    if (numbers.length <= 3 && letters.length <= 1) {
        return [numbers, letters];
    } else {
        return ["   ", " "];
    }
}

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