import { Component, EventEmitter, Inject, Input, OnInit, Output } from '@angular/core';
import { PCCEquipmentsListResponse, TrainOccupationsListItem, TrainOccupationsListResponse } from '../../../interfaces/equipment-management.interface';
import { DOCUMENT } from '@angular/common';
import { EncService } from '../../../services/enc.service';
import { ResourcesService } from '../../../services/resources.service';
import { EquipmentManagementService } from '../../../services/equipment-management.service';
import { MatDialog } from '@angular/material/dialog';
import { lastValueFrom } from 'rxjs';
import { LineLocationComponent } from './line-location/line-location.component';
import { TrainLocationComponent } from './train-location/train-location.component';
import { PccLocationComponent } from './pcc-location/pcc-location.component';
import { SystemAdminService } from '../../../services/system-admin.service';
import { StationPlanesListItem, StationPlanesListResponse } from '../../system-admin/system-params/system-params.component';
import { GdelService } from '../../../services/gdel.service';
import { StationViewDetailedComponent } from './station-view-detailed/station-view-detailed.component';
import { StationViewDetailedLocation } from './station-vew-position/station-vew-position.component';
import { ViaLevelSelectorComponent } from './via-level-selector/via-level-selector.component';
import { StationLocationComponent } from './station-location/station-location.component';

export interface ViaLocationPositions{
  index: number;
  name: string;
  type: string;
  stationInd: string;
  width: number;
  start: number;
  end: number;
}
export const VIA_POSITIONS: ViaLocationPositions[] = [
  {index: 0, name: 'Tapón Observatorio', type: 'I', stationInd: '', width: 41.88, start: 0, end: 670.08 },
  {index: 1, name: 'Observatorio', type: 'E', stationInd: '01', width: 18, start: 670.08, end: 958.08 },
  {index: 2, name: 'Observatorio - Tacubaya', type: 'I', stationInd: '', width: 151.32, start: 958.08, end: 3379.2 },
  {index: 3, name: 'Tacubaya', type: 'E', stationInd: '02', width: 18, start: 3379.2, end: 3667.2 },
  {index: 4, name: 'Tacubaya - Juanacatlán', type: 'I', stationInd: '', width: 138.96, start: 3667.2, end: 5890.56 },
  {index: 5, name: 'Juanacatlán', type: 'E', stationInd: '03', width: 18, start: 5890.56, end: 6178.56 },
  {index: 6, name: 'Juanacatlán - Chapultepec', type: 'I', stationInd: '', width: 116.64, start: 6178.56, end: 8044.8 },
  {index: 7, name: 'Chapultepec', type: 'E', stationInd: '04', width: 18, start: 8044.8, end: 8332.8 },
  {index: 8, name: 'Chapultepec - Sevilla', type: 'I', stationInd: '', width: 59.88, start: 8332.8, end: 9294.72 },
  {index: 9, name: 'Sevilla', type: 'E', stationInd: '05', width: 18.24, start: 9294.72, end: 9582.72 },
  {index: 10, name: 'Sevilla - Insurgentes', type: 'I', stationInd: '', width: 77.4, start: 9582.72, end: 10821.12 },
  {index: 11, name: 'Insurgentes', type: 'E', stationInd: '06', width: 18, start: 10821.12, end: 11107.2 },
  {index: 12, name: 'Insurgentes - Cuauhtémoc', type: 'I', stationInd: '', width: 95.16, start: 11107.2, end: 12631.68 },
  {index: 13, name: 'Cuauhtémoc', type: 'E', stationInd: '07', width: 17.88, start: 12631.68, end: 12917.76 },
  {index: 14, name: 'Cuauhtémoc - Balderas', type: 'I', stationInd: '', width: 49.08, start: 12917.76, end: 13703.04 },
  {index: 15, name: 'Balderas', type: 'E', stationInd: '08', width: 18.24, start: 13703.04, end: 13992.96 },
  {index: 16, name: 'Balderas - Salto del Agua', type: 'I', stationInd: '', width: 54.48, start: 13992.96, end: 14872.32 },
  {index: 17, name: 'Salto del Agua', type: 'E', stationInd: '09', width: 18.12, start: 14872.32, end: 15162.24 },
  {index: 18, name: 'Salto del Agua - Isabel la Católica', type: 'I', stationInd: '', width: 53.04, start: 15162.24, end: 16012.8 },
  {index: 19, name: 'Isabel la Católica', type: 'E', stationInd: '10', width: 18.12, start: 16012.8, end: 16304.64 },
  {index: 20, name: 'Isabel la Católica - Pino Suárez', type: 'I', stationInd: '', width: 45.72, start: 16304.64, end: 17026.56 },
  {index: 21, name: 'Pino Suárez', type: 'E', stationInd: '11', width: 18.36, start: 17026.56, end: 17314.56 },
  {index: 22, name: 'Pino Suárez - Merced', type: 'I', stationInd: '', width: 89.4, start: 17314.56, end: 18743.04 },
  {index: 23, name: 'Merced', type: 'E', stationInd: '12', width: 17.76, start: 18743.04, end: 19032.96 },
  {index: 24, name: 'Merced - Candelaria', type: 'I', stationInd: '', width: 83.88, start: 19032.96, end: 20376.96 },
  {index: 25, name: 'Candelaria', type: 'E', stationInd: '13', width: 18, start: 20376.96, end: 20664.96 },
  {index: 26, name: 'Candelaria - San Lázaro', type: 'I', stationInd: '', width: 104.04, start: 20664.96, end: 22337.28 },
  {index: 27, name: 'San Lázaro', type: 'E', stationInd: '14', width: 18, start: 22337.28, end: 22625.28 },
  {index: 28, name: 'San Lázaro - Moctezuma', type: 'I', stationInd: '', width: 57.24, start: 22625.28, end: 23527.68 },
  {index: 29, name: 'Moctezuma', type: 'E', stationInd: '15', width: 18.24, start: 23527.68, end: 23817.6 },
  {index: 30, name: 'Moctezuma - Balbuena', type: 'I', stationInd: '', width: 84.12, start: 23817.6, end: 25165.44 },
  {index: 31, name: 'Balbuena', type: 'E', stationInd: '16', width: 18.24, start: 25165.44, end: 25455.36 },
  {index: 32, name: 'Balbuena - Boulevard Puerto Aéreo', type: 'I', stationInd: '', width: 71.4, start: 25455.36, end: 26597.76 },
  {index: 33, name: 'Boulevard Puerto Aéreo', type: 'E', stationInd: '17', width: 17.88, start: 26597.76, end: 26885.76 },
  {index: 34, name: 'Boulevard Puerto Aéreo - Gómez Farías', type: 'I', stationInd: '', width: 73.32, start: 26885.76, end: 28056.96 },
  {index: 36, name: 'Gómez Farías', type: 'E', stationInd: '18', width: 18, start: 28056.96, end: 28346.88 },
  {index: 37, name: 'Gómez Farías - Zaragoza', type: 'I', stationInd: '', width: 91.32, start: 28346.88, end: 29808 },
  {index: 38, name: 'Zaragoza', type: 'E', stationInd: '19', width: 18.24, start: 29808.0, end: 30097.92 },
  {index: 39, name: 'Zaragoza - Pantitlán', type: 'I', stationInd: '', width: 158.28, start: 30097.92, end: 32638.08 },
  {index: 40, name: 'Pantitlán', type: 'E', stationInd: '20', width: 17.88, start: 32638.08, end: 32926.08 },
  {index: 41, name: 'Tapón Pantitlán', type: 'I', stationInd: '', width: 72.24, start: 32926.08, end: 34080 },
];
export interface StationLevelsPlanes{
  id: string,
  name: string,
  url: string,
  level: string,
  families: StationLevelsPlaneFamilies[],
}
export interface StationLevelsPlaneFamilies{
  originCoords: string | null,
  destinyCoords: string | null,
  originKM: number,
  destinyKM: number,
  color: string,
  name: string,
}
@Component({
    selector: 'app-equipment-location',
    templateUrl: './equipment-location.component.html',
    styleUrl: './equipment-location.component.css',
    standalone: false
})
export class EquipmentLocationComponent implements OnInit {
  @Input() locatingCoords!: string;
  @Input() coordsType!: string;
  @Output() returnCoords = new EventEmitter<string>();
  locationTypeModel: string;

  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  codeType: string;
  searchingTrainOccupations: boolean;
  carType: string;
  areaIndicator: string;
  viewIndex: number;
  trainOccupation: string;
  viaPositions = VIA_POSITIONS;
  currentStationIndex: number;
  currentStationType: string;
  displayVia: boolean;
  stationViewESVal: number | undefined;
  stationViewHovered: string;
  searchingStationPlans: boolean;
  stationPlaneSelected: string;
  stationPlaneSelectedURL: string;
  showCoords: boolean;
  selectedCoordX: string;
  locationType: string;
  coordHeight: number;
  coordWidth: number;
  stationViewLevel: string;
  pccSelectedXCoord: string;
  searchingPCCEquipments: boolean;

  lineImages: any[];
  trainOccupations: TrainOccupationsListItem[];
  viaImages: string[];
  rulerSpacers: number[];
  stationLevelsPlanes: StationLevelsPlanes[];
  stationLevelCoordsY: string[];
  stationLevelCoordsX: string[];
  detailCoordsX: string[];
  detailCoordsY: string[];
  locationCoords: StationViewDetailedLocation[];
  coordsPixels: string[];
  pccCoordsY: string[];
  pccCoordsX: string[];
  pccFamilies: StationLevelsPlaneFamilies[];

  viewAreas = ['Vista lateral', 'Vista superior', 'Vista inferior'];
  yCoords = ['-', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'Ñ', 'O', 'P', 'Q', 
  'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AB'];
  xCoords = ['-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16',
  '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27'];
  coords = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 
  'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

  map: Map<string, any>;
  elements = [
    {coord: '0N',  element: 'PDC',                                     code: 'PDCXX', color: '#337a91'},
    {coord: '1F',  element: 'BAT',                                     code: 'BATXX', color: '#8e3596'},
    {coord: '1I',  element: 'BAT',                                     code: 'BATXX', color: '#cfc763'},
    {coord: '1R',  element: 'SAP/IHM OA',                              code: 'SAIOA', color: '#3ba896'},
    {coord: '2F',  element: 'UPS',                                     code: 'UPSXX', color: '#d4735b'},
    {coord: '2I',  element: 'UPS',                                     code: 'UPSXX', color: '#e62e34'},
    {coord: '2R',  element: 'PIU/DDP',                                 code: 'PIUDD', color: '#065240'},
    {coord: '2V',  element: 'ODF',                                     code: 'ODFXX', color: '#94e687'},
    {coord: '3F',  element: 'BAT',                                     code: 'BATXX', color: '#05c9f0'},
    {coord: '3I',  element: 'BAT',                                     code: 'BATXX', color: '#574494'},
    {coord: '3Ñ',  element: 'SRV-COMMS PCC-A',                         code: 'SRCPA', color: '#4dd907'},
    {coord: '3R',  element: 'CCTV',                                    code: 'CCTVX', color: '#3d36ba'},
    {coord: '4F',  element: 'BAT',                                     code: 'BATXX', color: '#9336ba'},
    {coord: '4I',  element: 'BAT',                                     code: 'BATXX', color: '#ba8336'},
    {coord: '4Ñ',  element: 'SRV-COMMS PCC-B',                         code: 'SRCPB', color: '#a9ba36'},
    {coord: '4R',  element: 'LTE',                                     code: 'LTEXX', color: '#36ba4e'},
    {coord: '4V',  element: 'AC',                                      code: 'ACXXX', color: '#ba4336'},
    {coord: '5Ñ',  element: 'SRV-COMMS PCC-C',                         code: 'SRCPC', color: '#a1107f'},
    {coord: '6F',  element: 'UPS',                                     code: 'UPSXX', color: '#c781b7'},
    {coord: '6I',  element: 'UPS',                                     code: 'UPSXX', color: '#060733'},
    {coord: '6R',  element: 'TEL/GDA',                                 code: 'TELGD', color: '#173306'},
    {coord: '6V',  element: 'AC',                                      code: 'ACXXX', color: '#06332a'},
    {coord: '7Ñ',  element: 'SCADA E&M',                               code: 'SCAEM', color: '#47edcc'},
    {coord: '7R',  element: 'CLK/CDA',                                 code: 'CLKCD', color: '#1629f7'},
    {coord: '8B',  element: 'INTERRUPTOR ELECTROMAGNÉTICO 3x1600 AMP', code: 'IE316', color: '#f0f716'},
    {coord: '8R',  element: 'RMS',                                     code: 'RMSXX', color: '#f71629'},
    {coord: '9V',  element: 'LTE-B',                                   code: 'LTEBX', color: '#8e16f7'},
    {coord: '10B', element: 'TRANSFORMADOR TIPO SECO 500 KVA',         code: 'TTS5K', color: '#f716e8'},
    {coord: '11U', element: 'ARMARIOS RECUPERACIÓN DE MANDO L1 A L6',  code: 'ARM16', color: '#f78316'},
    {coord: '11V', element: 'ARMARIOS RECUPERACIÓN DE MANDO L1 A L6',  code: 'ARM16', color: '#3cf716'},
    {coord: '11W', element: 'MDF',                                     code: 'MDFXX', color: '#167cf7'},
    {coord: '11Y', element: 'ODF',                                     code: 'ODFXX', color: '#c7f716'},
    {coord: '12F', element: 'UPS',                                     code: 'UPSXX', color: '#576620'},
    {coord: '12J', element: 'COBRE',                                   code: 'COBRE', color: '#205266'},
    {coord: '12L', element: 'COBRE',                                   code: 'COBRE', color: '#382066'},
    {coord: '12M', element: 'COBRE',                                   code: 'COBRE', color: '#663720'},
    {coord: '12Ñ', element: 'RED',                                     code: 'REDXX', color: '#662022'},
    {coord: '12O', element: 'RED',                                     code: 'REDXX', color: '#337a91'},
    {coord: '12Q', element: 'RED',                                     code: 'REDXX', color: '#8e3596'},
    {coord: '13B', element: 'TABLERO A',                               code: 'TABLA', color: '#cfc763'},
    {coord: '14F', element: 'BAT',                                     code: 'BATXX', color: '#3ba896'},
    {coord: '15F', element: 'UPS',                                     code: 'UPSXX', color: '#d4735b'},
    {coord: '15K', element: 'CCTV L1 A L6',                            code: 'CCT16', color: '#e62e34'},
    {coord: '15Ñ', element: 'RED C Y S L1 A L6',                       code: 'RCS16', color: '#065240'},
    {coord: '15W', element: 'TRACCIÓN',                                code: 'TRACC', color: '#94e687'},
    {coord: '16B', element: 'TABLERO P',                               code: 'TABLP', color: '#05c9f0'},
    {coord: '16F', element: 'BAT',                                     code: 'BATXX', color: '#574494'},
    {coord: '16K', element: 'CCTV L1 A L6',                            code: 'CCT16', color: '#4dd907'},
    {coord: '16Ñ', element: 'RED C Y S L1 A L6',                       code: 'RCS16', color: '#3d36ba'},
    {coord: '16W', element: 'TRACCIÓN',                                code: 'TRACC', color: '#9336ba'},
    {coord: '17W', element: 'DISTRIBUCIÓN DE ENERGÍA L2',              code: 'DIEL2', color: '#ba8336'},
    {coord: '19B', element: 'TABLERO B',                               code: 'TABLB', color: '#a9ba36'},
    {coord: '19K', element: 'TELECOM L2',                              code: 'TELL2', color: '#36ba4e'},
    {coord: '19Ñ', element: 'SERVIDOR BASE DE DATOS L2',               code: 'SBDL2', color: '#ba4336'},
    {coord: '19R', element: 'SERVIDOR DE APLICACIONES L2',             code: 'SEAL2', color: '#a1107f'},
    {coord: '19W', element: 'DISTRIBUCIÓN DE ENERGÍA L3',              code: 'DIEL3', color: '#c781b7'},
    {coord: '20F', element: 'UPS',                                     code: 'UPSXX', color: '#060733'},
    {coord: '20K', element: 'TELECOM L3',                              code: 'TELL3', color: '#173306'},
    {coord: '20Ñ', element: 'SERVIDOR BASE DE DATOS L3',               code: 'SBDL3', color: '#06332a'},
    {coord: '20R', element: 'SERVIDOR DE APLICACIONES L3',             code: 'SEAL3', color: '#47edcc'},
    {coord: '20W', element: 'DISTRIBUCIÓN DE ENERGÍA L4',              code: 'DIEL4', color: '#1629f7'},
    {coord: '21B', element: 'TRANSFORMADOR TIPO SECO 500 KVA',         code: 'TTS5K', color: '#f0f716'},
    {coord: '21F', element: 'BAT',                                     code: 'BATXX', color: '#f71629'},
    {coord: '22F', element: 'UPS',                                     code: 'UPSXX', color: '#8e16f7'},
    {coord: '22K', element: 'TELECOM L4',                              code: 'TELL4', color: '#f716e8'},
    {coord: '22Ñ', element: 'SERVIDOR BASE DE DATOS L4',               code: 'SBDL4', color: '#f78316'},
    {coord: '22R', element: 'SERVIDOR DE APLICACIONES L4',             code: 'SEAL4', color: '#3cf716'},
    {coord: '22W', element: 'DISTRIBUCIÓN DE ENERGÍA L5',              code: 'DIEL5', color: '#167cf7'},
    {coord: '23F', element: 'BAT',                                     code: 'BATXX', color: '#c7f716'},
    {coord: '23K', element: 'TELECOM L5',                              code: 'TELL5', color: '#576620'},
    {coord: '23Ñ', element: 'SERVIDOR BASE DE DATOS L5',               code: 'SBDL5', color: '#205266'},
    {coord: '23R', element: 'SERVIDOR DE APLICACIONES L5',             code: 'SEAL5', color: '#382066'},
    {coord: '24B', element: 'INTERRUPTOR ELECTROMAGNÉTICO 3x1600 AMP', code: 'IE316', color: '#663720'},
    {coord: '24K', element: 'TELECOM L6',                              code: 'TELL6', color: '#662022'},
    {coord: '24Ñ', element: 'SERVIDOR BASE DE DATOS L6',               code: 'SBDL6', color: '#827474'},
    {coord: '24R', element: 'SERVIDOR DE APLICACIONES L6',             code: 'SEAL6', color: '#b4aae6'},
    {coord: '24W', element: 'DISTRIBUCIÓN DE ENERGÍA L6',              code: 'DIEL6', color: '#120d2e'},
  ];

  constructor(
    @Inject(DOCUMENT) private _document: Document,
    private _encService: EncService,
    private _resourcesService: ResourcesService,
    private _equipmentManagementService: EquipmentManagementService,
    private _dialog: MatDialog,
    private _systemAdminService: SystemAdminService,
    private _gdelService: GdelService,
  ){
    this.locationTypeModel = '';
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    this.codeType = '';
    this.searchingTrainOccupations = false;
    this.carType = '';
    this.areaIndicator = '';
    this.viewIndex = 0;
    this.trainOccupation = '';
    this.currentStationIndex = 0;
    this.currentStationType = 'I';
    this.displayVia = false;
    this.stationViewESVal = undefined;
    this.stationViewHovered = '';
    this.searchingStationPlans = false;
    this.stationPlaneSelected = '';
    this.stationPlaneSelectedURL = '';
    this.showCoords = false;
    this.selectedCoordX = '';
    this.locationType = '';
    this.coordHeight = 0;
    this.coordWidth = 0;
    this.stationViewLevel = '';
    this.pccSelectedXCoord = '';
    this.searchingPCCEquipments = false;

    this.lineImages = [];
    this.trainOccupations = [];
    this.viaImages = [];
    this.rulerSpacers = [];
    this.stationLevelsPlanes = [];
    this.stationLevelCoordsY = [];
    this.stationLevelCoordsX = [];
    this.detailCoordsX = [];
    this.detailCoordsY = [];
    this.coordsPixels = [];
    this.pccCoordsX = [];
    this.pccCoordsY = [];
    this.pccFamilies = [];
    this.map = new Map();
    this.locationCoords = [
      { idCoord: 'SI', nameCoord: 'Superior izquierda', left: true, top: true, right: true, bottom: true },
      { idCoord: 'SM', nameCoord: 'Superior media', left: false, top: true, right: true, bottom: true },
      { idCoord: 'SD', nameCoord: 'Superior derecha', left: false, top: true, right: true, bottom: true },
      { idCoord: 'CI', nameCoord: 'Central izquierda', left: true, top: false, right: true, bottom: true },
      { idCoord: 'CM', nameCoord: 'Central media', left: false, top: false, right: true, bottom: true },
      { idCoord: 'CD', nameCoord: 'Central derecha', left: false, top: false, right: true, bottom: true },
      { idCoord: 'II', nameCoord: 'Inferior izquierda', left: true, top: false, right: true, bottom: true },
      { idCoord: 'IM', nameCoord: 'Inferior media', left: false, top: false, right: true, bottom: true },
      { idCoord: 'ID', nameCoord: 'Inferior derecha', left: false, top: false, right: true, bottom: true },
    ];
  }

  ngOnInit(): void {
    if(this.locatingCoords == 'S'){
      this.locationTypeModel = 'ES';
      setTimeout(() => {
        for(const item of this.viaPositions){
          if(item.type == 'E'){
            let itemObj = this._document.getElementById(`EST-${item.stationInd}`)!;
            itemObj.addEventListener('mouseover', () => {
              this.stationViewHovered = item.stationInd;
            });

            itemObj.addEventListener('mouseout', () => {
              this.stationViewHovered = '';
            });
          }
        }
      }, 100);
    }

    for(let x = 0; x < this.xCoords.length; x++){
      let xCoord = this.xCoords[x];
      for(let y = 0; y < this.yCoords.length; y++){
        let yCoord = this.yCoords[y];
        let coord = `${xCoord}${yCoord}`;

        let element = this.elements.filter(item => item.coord == coord);
        if(element.length > 0){
          this.map.set(coord, element[0]);
        }
      }
    }

    for(let i = 1; i <= 177; i++){
      let indexStr = `${i}`;
      for(let j = indexStr.length; j < 3; j++){
        indexStr = `0${indexStr}`;
      }

      this.viaImages.push(indexStr);
    }

    for(let i = 1; i <= 9; i++){
      this.rulerSpacers.push(i);
    }

    for(let i = 0; i < 25; i++){
      let coord = this.coords[i];
      this.stationLevelCoordsY.push(coord);
    }

    for(let i = 0; i < 10; i++){
      this.detailCoordsX.push(`${i}`);
      this.detailCoordsY.push(`${i}`);
    }

    this.detailCoordsY.reverse();
    this.stationLevelCoordsY.reverse();
  }

  goBack(steps: number){
    if(this.locatingCoords == 'S'){
      this.coordsLocated('');
    }else{
      window.history.go(steps * -1);
    }
  }

  locationTypeChange(event: any){
    this.locationType = event.value;

    if(event.value == 'TR'){
      this.getTrainOccupations();
    }else if(event.value == 'ES'){
      setTimeout(() => {
        for(const item of this.viaPositions){
          if(item.type == 'E'){
            let itemObj = this._document.getElementById(`EST-${item.stationInd}`)!;
            itemObj.addEventListener('mouseover', () => {
              this.stationViewHovered = item.stationInd;
            });

            itemObj.addEventListener('mouseout', () => {
              this.stationViewHovered = '';
            });
          }
        }
      }, 100);
    }else if(event.value == 'PC'){
      this.getPCCEquipments();
    }

    if(event.value == 'VI'){
      this.searchViaEquipments();
    }
  }

  private async getPCCEquipments(){
    try{
      this.searchingPCCEquipments = true;

      let idUser = localStorage.getItem('idusuario')!;
      let equipments: PCCEquipmentsListResponse = await lastValueFrom(this._equipmentManagementService.equipmentConsultPCC(idUser, 1));

      if(equipments.error){
        this._resourcesService.openSnackBar(equipments.msg);
      }else{
        let planeFamilies: StationLevelsPlaneFamilies[] = [];

        for(const family of equipments.response){
          let familyCoordsArr = family.COLOR_COORDENADAS.split('|');
          if(familyCoordsArr.length == 3){
            let familyObj: StationLevelsPlaneFamilies = {
              originCoords: familyCoordsArr[0] == '-' ? null : familyCoordsArr[0],
              destinyCoords: null,
              originKM: 0,
              destinyKM: 0,
              color: familyCoordsArr[1],
              name: `${familyCoordsArr[2]} (${family.FAMILIA})`,
            }

            planeFamilies.push(familyObj);
          }
        }

        this.pccFamilies = planeFamilies;
      }

      this.searchingPCCEquipments = false;
      this.initPCCInterface();
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (1).');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (2).');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }

      this.searchingPCCEquipments = false;
    }
  }

  private initPCCInterface(){
    setTimeout(() => {
      let pccCoordsContainer = this._document.getElementById('pcc-coords-container') as HTMLElement;
      pccCoordsContainer.style.width = `${pccCoordsContainer.offsetHeight}px`;

      let coordSize = pccCoordsContainer.offsetHeight / (this.coords.length + 1);
      let coordsYAux: string[] = [];

      for(const coord of this.coords){
        coordsYAux.push(coord);
      }

      coordsYAux.reverse();
      coordsYAux.push('');
      
      this.pccCoordsY = coordsYAux;
      let pccYCoordsContainer = this._document.getElementById('pcc-y-coords-container') as HTMLElement;
      pccYCoordsContainer.style.width = `${coordSize}px`;

      setTimeout(() => {
        let pccYCoords = this._document.getElementsByClassName('pcc-y-coord');
        for(let i = 0; i < pccYCoords.length; i++){
          let item = pccYCoords.item(i) as HTMLElement;
          item.style.height = `${coordSize}px`;
          item.style.maxHeight = `${coordSize}px`;
          item.style.minHeight = `${coordSize}px`;
        }

        let pccXCoordsMainContainer = this._document.getElementById('pcc-x-coords-main-container') as HTMLElement;
        pccXCoordsMainContainer.style.width = `${pccCoordsContainer.offsetHeight - coordSize}px`;

        let pccXCoordsContainer = this._document.getElementById('pcc-x-coords-container') as HTMLElement;
        pccXCoordsContainer.style.height = `${coordSize}px`;

        let coordsXAux: string[] = [];
        for(const coord of this.coords){
          coordsXAux.push(`A${coord}`);
        }

        this.pccCoordsX = coordsXAux;
        setTimeout(() => {
          let pccXCoords = this._document.getElementsByClassName('pcc-x-coord');
          for(let i = 0; i < pccXCoords.length; i++){
            let item = pccXCoords.item(i) as HTMLElement;
            item.style.width = `${coordSize}px`;
          }

          let pccPlaneContainer = this._document.getElementById('pcc-plane-container') as HTMLElement;
          pccPlaneContainer.style.height = `${pccCoordsContainer.offsetHeight - coordSize}px`;

          let pccXIndicators = this._document.getElementsByClassName('pcc_x_indicator');
          for(let i = 0; i < pccXIndicators.length; i++){
            let item = pccXIndicators.item(i) as HTMLElement;
            item.style.width = `${coordSize}px`;
          }

          let  pccCoordsY = this._document.getElementsByClassName('pcc_coord_y');
          for(let i = 0; i < pccCoordsY.length; i++){
            let item = pccCoordsY.item(i) as HTMLElement;
            item.style.height = `${coordSize}px`;
          }
        }, 100);
      }, 100);
    }, 100);
  }

  selectPCCXCoord(coordX: string){
    if(this.pccSelectedXCoord == ''){
      this.pccSelectedXCoord = coordX;

      let indicator = this._document.getElementById(`pcc_x_indicator${coordX}`) as HTMLElement;
      setTimeout(() => {
        let yIndicators = this._document.getElementsByClassName('pcc_y_indicator');
        for(let i = 0; i < yIndicators.length; i++){
          let item = yIndicators.item(i) as HTMLElement;
          item.style.height = `${indicator.offsetHeight / yIndicators.length}px`;
        }
      }, 100);
    }else{
      this.pccSelectedXCoord = '';
      this.initPCCInterface();
    }
  }

  private async searchViaEquipments(){
    try{
      this.searchingPCCEquipments = true;

      let idUser = localStorage.getItem('idusuario')!;
      let viaEquipments: PCCEquipmentsListResponse = await lastValueFrom(this._equipmentManagementService.equipmentConsultVia(
        idUser,
        1
      ));

      if(viaEquipments.error){
        this._resourcesService.openSnackBar(viaEquipments.msg);
      }else{
        let planeFamilies: StationLevelsPlaneFamilies[] = [];

        for(const family of viaEquipments.response){
          let familyCoordsArr = family.COLOR_COORDENADAS.split('|');
          if(familyCoordsArr.length == 4){
            let familyObj: StationLevelsPlaneFamilies = {
              originCoords: familyCoordsArr[0] == '-' ? null : familyCoordsArr[0],
              destinyCoords: familyCoordsArr[1] == '-' ? null : familyCoordsArr[1],
              originKM: familyCoordsArr[0] == '-' ? -1 : parseFloat(familyCoordsArr[0]),
              destinyKM: familyCoordsArr[1] == '-' ? -1 : parseFloat(familyCoordsArr[1]),
              color: familyCoordsArr[2],
              name: `${familyCoordsArr[3]} (${family.FAMILIA})`,
            }

            planeFamilies.push(familyObj);
          }
        }

        this.pccFamilies = planeFamilies;
      }
      
      this.searchingPCCEquipments = false;
      this.setViaScrollListener();
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (3).');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (4).');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
      
      this.searchingPCCEquipments = false;
      this.setViaScrollListener();
    }
  }

  private setViaScrollListener(){
    setTimeout(() => {
      let viaElementsContainer = this._document.getElementById('via-elements-container')!;
      let rulerElementsContainer = this._document.getElementById('ruler-elements-container')!;
      let topElementsContainer = this._document.getElementById('top-elements-container')!;
      let bottomElementsContainer = this._document.getElementById('bottom-elements-container')!;
      let positionIndicatorContainer = this._document.getElementById('position-indicator-container')!;

      rulerElementsContainer.scrollLeft = 0;
      topElementsContainer.scrollLeft = 0;
      bottomElementsContainer.scrollLeft = 0;

      if(viaElementsContainer.scrollWidth < rulerElementsContainer.scrollWidth){
        this.setViaScrollListener();
        return;
      }

      let positionIndicator = this._document.getElementById('position-indicator')!;
      let positionIndicatorContainerPercent = (positionIndicatorContainer.offsetWidth * 1) / viaElementsContainer.scrollWidth;
      let positionIndicatorWidth = positionIndicatorContainerPercent * positionIndicatorContainer.offsetWidth;
      positionIndicator.style.width = `${positionIndicatorWidth}px`;
      this.displayVia = true;

      viaElementsContainer.addEventListener('wheel', (event: any) => {
        if(event.deltaY > 0){
          viaElementsContainer.scrollLeft += 50;
          event.preventDefault();
        }else{
          viaElementsContainer.scrollLeft -= 50;
          event.preventDefault();
        }
      });

      rulerElementsContainer.addEventListener('wheel', (event: any) => {
        if(event.deltaY > 0){
          rulerElementsContainer.scrollLeft += 50;
          event.preventDefault();
        }else{
          rulerElementsContainer.scrollLeft -= 50;
          event.preventDefault();
        }
      });

      viaElementsContainer.addEventListener('scroll', (_: any) => {
        rulerElementsContainer.scrollLeft = viaElementsContainer.scrollLeft;
        topElementsContainer.scrollLeft = viaElementsContainer.scrollLeft;
        bottomElementsContainer.scrollLeft = viaElementsContainer.scrollLeft;
        
        let indicatorLeft = ((positionIndicatorContainer.scrollWidth) * viaElementsContainer.scrollLeft) / viaElementsContainer.scrollWidth;
        positionIndicator.style.left = `${indicatorLeft}px`;

        let indicatorLeftPercent = ((indicatorLeft * viaElementsContainer.scrollWidth) / positionIndicatorContainer.offsetWidth) + 48;
        let displayedElements = this.viaPositions.filter(item => item.end >= indicatorLeftPercent);
        
        this.currentStationIndex = displayedElements[0].index;
        this.currentStationType = displayedElements[0].type;
      });

      rulerElementsContainer.addEventListener('scroll', (_: any) => {
        viaElementsContainer.scrollLeft = rulerElementsContainer.scrollLeft;
        topElementsContainer.scrollLeft = viaElementsContainer.scrollLeft;
        bottomElementsContainer.scrollLeft = rulerElementsContainer.scrollLeft;
      });
    }, 1000);
  }

  private async getTrainOccupations(){
    try{
      this.searchingTrainOccupations = true;
      
      let idUser = localStorage.getItem('idusuario')!;
      let trainOccupations: TrainOccupationsListResponse = await lastValueFrom(this._equipmentManagementService.occupationTrainConsult(idUser, 1));

      if(trainOccupations.error){
        this._resourcesService.openSnackBar(trainOccupations.msg);
      }else{
        let trainOccupationsArr: TrainOccupationsListItem[] = [];
        for(const occupation of trainOccupations.response){
          let carDec = await this._encService.decrypt(occupation.CAR);
          let codeDec = await this._encService.decrypt(occupation.CODE);

          occupation.CAR = `${carDec} (${codeDec})`;
          trainOccupationsArr.push(occupation);
        }

        this.trainOccupations = trainOccupationsArr;
      }

      this.searchingTrainOccupations = false;
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (5).');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (6).');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }

      this.searchingTrainOccupations = false;
    }
  }

  async trainOccupationChange(occupation: string){
    try{
      this.searchingPCCEquipments = true;

      let idUser = localStorage.getItem('idusuario')!;
      let occupationEquipments: PCCEquipmentsListResponse = await lastValueFrom(this._equipmentManagementService.equipmentConsultTrain(
        occupation,
        idUser,
        1
      ));

      if(occupationEquipments.error){
        this._resourcesService.openSnackBar(occupationEquipments.msg);
      }else{
        let planeFamilies: StationLevelsPlaneFamilies[] = [];

        for(const family of occupationEquipments.response){
          let familyCoordsArr = family.COLOR_COORDENADAS.split('|');
          if(familyCoordsArr.length == 3){
            let familyObj: StationLevelsPlaneFamilies = {
              originCoords: familyCoordsArr[0] == '-' ? null : familyCoordsArr[0],
              destinyCoords: null,
              originKM: 0,
              destinyKM: 0,
              color: familyCoordsArr[1],
              name: `${familyCoordsArr[2]} (${family.FAMILIA})`,
            }

            planeFamilies.push(familyObj);
          }
        }

        this.pccFamilies = planeFamilies;
      }
      
      this.trainOccupation = occupation;
      
      let occupationDec = await this._encService.decrypt(occupation);
      let occupationArr = occupationDec.split('-');
      if(occupationArr[0] == 'RC1' || occupationArr[0] == 'RC2'){
        this.carType = 'RC';
      }else if(occupationArr[0] == 'N1' || occupationArr[0] == 'N2' || occupationArr[0] == 'N3' 
      || occupationArr[0] == 'N4' || occupationArr[0] == 'N5' || occupationArr[0] == 'N6'){
        this.carType = 'N';
        let trainNumberStr = occupationArr[0].replace('N', '');
        if(trainNumberStr == '1' || trainNumberStr == '6'){
          this.areaIndicator = '2';
        }else if(trainNumberStr == '2' || trainNumberStr == '5'){
          this.areaIndicator = '3';
        }else if(trainNumberStr == '3' || trainNumberStr == '4'){
          this.areaIndicator = '4';
        }
      }else if(occupationArr[0] == 'R'){
        this.carType = 'R';
      }else{
        this._resourcesService.openSnackBar(`La ocupación de tren ${occupationDec} es inválida.`);
      }
      
      this.searchingPCCEquipments = false;
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (7).');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (8).');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
      
      this.searchingPCCEquipments = false;
    }
  }

  openPKEquipments(startKM: string | number, endKM: string | number){
    let startKMNum: number = typeof startKM == 'string' ? parseFloat(startKM) : startKM;
    let endKMNum: number = typeof endKM == 'string' ? parseFloat(endKM) : endKM;

    let dialogRef = this._dialog.open(ViaLevelSelectorComponent, {
      width: '640px',
      maxWidth: '640px',
      data: {
        startKM: startKMNum,
        endKM: endKMNum
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res != null && res != undefined && res != ''){
        let infoObj = {
          startKM: startKMNum,
          endKM: endKMNum,
          level: res,
        };

        let infoStr = JSON.stringify(infoObj);
        this._dialog.open(LineLocationComponent, {
          width: '640px',
          maxWidth: '640px',
          data: {
            info: infoStr
          }
        });
      }
    });
  }

  goBackward(){
    let indTmp = this.viewIndex - 1;
    if(indTmp < 0){
      this.viewIndex = this.viewAreas.length - 1;
    }else{
      this.viewIndex--;
    }
  }

  goForward(){
    let indTmp = this.viewIndex + 1;
    if(indTmp >= this.viewAreas.length){
      this.viewIndex = 0;
    }else{
      this.viewIndex++;
    }
  }

  async returnTrainArea(areaStr: string){
    let areaEnc = await this._encService.encrypt(areaStr);
    this._dialog.open(TrainLocationComponent, {
      width: '640px',
      maxWidth: '640px',
      data: {
        car: this.trainOccupation,
        area: areaEnc,
      },
    });
  }

  async openPCCEquipments(coordX: string, coordY: string){
    let infoObj = {
      coordX: coordX,
      coordY: coordY,
    };

    let infoStr = JSON.stringify(infoObj);
    let infoEnc = await this._encService.encrypt(infoStr);

    this._dialog.open(PccLocationComponent, {
      width: '640px',
      maxWidth: '640px',
      data: {
        element: infoEnc,
      },
    });
  }

  locationChange(event: any){
    let viaElementsContainer = this._document.getElementById('via-elements-container')!;
    let elementFilt = this.viaPositions.filter(item => item.index == event);

    if(elementFilt.length > 0){
      viaElementsContainer.scrollLeft = elementFilt[0].start - 48;
    }
  }

  moveVia(direction: string){
    let viaElementsContainer = this._document.getElementById('via-elements-container')!;
    if(direction == 'f'){
      viaElementsContainer.scrollLeft += 50;
    }else{
      viaElementsContainer.scrollLeft -= 50;
    }
  }

  selectStationViewESVal(stationIndex: number){
    this.stationViewESVal = stationIndex;
    this.changeStationViewESVal();
  }

  changeStationViewESVal(){
    let stationFilt = this.viaPositions.filter(item => item.index == this.stationViewESVal);
    if(stationFilt.length > 0){
      this.searchStationPlanes(stationFilt[0].stationInd);
    }
  }

  private async searchStationPlanes(stationInd: string){
    try{
      this.searchingStationPlans = true;
      this.stationPlaneSelected = '';

      let idUser = localStorage.getItem('idusuario')!;
      let stationIndEnc = await this._encService.encrypt(stationInd);
      let stationPlanes: StationPlanesListResponse = await lastValueFrom(this._systemAdminService.getStationPlanes(
        stationIndEnc,
        idUser,
        1
      ));

      if(stationPlanes.error){
        this._resourcesService.openSnackBar(stationPlanes.msg);
      }else{
        let stationLevelsPlanes: StationLevelsPlanes[] = [];
        for(const plane of stationPlanes.response){
          let idPlaneDec = await this._encService.decrypt(plane.ID_PLANO);
          let fileURI = await lastValueFrom(this._gdelService.getPublicDocumentUrl(plane.ARCHIVO_RELACIONADO, idUser, 1));
          if(fileURI.error){
            this._resourcesService.openSnackBar(fileURI.msg);
          }else{
            let planeFamilies: StationLevelsPlaneFamilies[] = [];
            for(const family of plane.FAMILIAS){
              let familyCoordsArr = family.COLOR_COORDENADAS.split('|');
              if(familyCoordsArr.length == 4){
                let familyObj: StationLevelsPlaneFamilies = {
                  originCoords: familyCoordsArr[0] == '-' ? null : familyCoordsArr[0],
                  destinyCoords: familyCoordsArr[1] == '-' ? null : familyCoordsArr[1],
                  originKM: 0,
                  destinyKM: 0,
                  color: familyCoordsArr[2],
                  name: `${familyCoordsArr[3]} (${family.FAMILIA})`,
                }

                planeFamilies.push(familyObj);
              }
            }
            
            let planeObj: StationLevelsPlanes = {
              id: idPlaneDec,
              name: await this._encService.decrypt(plane.ARCHIVO_RELACIONADO),
              url: fileURI.response.public_uri,
              level: plane.NIVEL,
              families: planeFamilies
            };
            
            stationLevelsPlanes.push(planeObj);
          }
        }

        this.stationLevelsPlanes = stationLevelsPlanes;
        if(this.stationLevelsPlanes.length > 0){
          let stationLevelsPlanesAnden = stationLevelsPlanes.filter(item => item.level == 'A');
          if(stationLevelsPlanesAnden.length > 0){
            this.stationPlaneSelected = stationLevelsPlanesAnden[0].id;
            this.stationPlaneSelectedURL = stationLevelsPlanesAnden[0].url;
            this.stationViewLevel = 'A';
          }else{
            let stationLevelsPlanesVestibulo = stationLevelsPlanes.filter(item => item.level == 'V');
            if(stationLevelsPlanesVestibulo.length > 0){
              this.stationPlaneSelected = stationLevelsPlanesVestibulo[0].id;
              this.stationPlaneSelectedURL = stationLevelsPlanesVestibulo[0].url;
              this.stationViewLevel = 'V';
            }
          }

          this.initPlaneView();
        }
      }

      this.searchingStationPlans = false;
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (9).');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (10).');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
      
      this.searchingStationPlans = false;
    }
  }

  stationViewLevelChange(){
    let levelPlanes = this.stationLevelsPlanes.filter(item => item.level == this.stationViewLevel);
    if(levelPlanes.length > 0){
      this.stationPlaneSelected = levelPlanes[0].id;
      this.stationPlaneSelectedURL = levelPlanes[0].url;

      this.initPlaneView();
    }else{
      this.stationPlaneSelected = '';
      this.stationPlaneSelectedURL = '';
    }
  }

  initPlaneView(){
    setTimeout(() => {
      this.showCoords = false;

      let stationViewPlaneY = this._document.getElementById('station-view-plane-y')!; //Se obtiene el contenedor de las coordenadas en Y
      let stationViewPlaneYHeight = stationViewPlaneY.offsetHeight - 2; //Se extrae el alto del contenedor y se restan 2 pixeles para los margenes horizontales
      let stationViewPlaneYItemHeight = stationViewPlaneYHeight / 25; //Se divide la altitud actual del contenedor entre el número total de coordenadas en Y

      let originalPlane = this._document.getElementById('plane-viewer')!; //Se obtiene el contenedor del plano original
      let originalPlaneSpan = originalPlane.children[0]!; //Se obtiene el span del contenedor del plano original
      let originalPlaneSvg = originalPlaneSpan.children[0]! as any; //Se obtiene el plano original en SVG
      
      //Si no se encuentra el plano original en SVG se termina la función y se invoca nuevamente
      if(originalPlaneSvg == undefined){
        this.initPlaneView();
        return
      }
      
      let originalPlaneSvgHeight = originalPlaneSvg.height.baseVal.value; //Se obtiene la altura original del plano
      let originalPlaneSvgWidth = originalPlaneSvg.width.baseVal.value; // Se obtiene el ancho original del plano
      
      let stationViewPlaneScale = this._document.getElementById('station-view-plane-scale')! as HTMLElement; //Se obtiene el contenedor del plano a escalar
      let stationViewPlaneScaleWidth = (stationViewPlaneScale.offsetHeight * originalPlaneSvgWidth) / originalPlaneSvgHeight; //Se calcula el ancho preliminar que tendrá el plano escalado
      let numCoordX = stationViewPlaneScaleWidth / stationViewPlaneYItemHeight; //Se calcula el número de coordenadas en X que tendrá el plano escalado
      let numCoordXInt = Math.trunc(numCoordX); //Se eliminan los decimales del número de coordenadas en X
      let planeSvgFinalWidth = numCoordXInt * stationViewPlaneYItemHeight; //Se calcula el ancho final del plano escalado

      //Se asigna el ancho final al plano escalado
      stationViewPlaneScale.style.minWidth = `${planeSvgFinalWidth}px`;
      stationViewPlaneScale.style.width = `${planeSvgFinalWidth}px`;
      
      let stationViewPlaneScaleHeight = (planeSvgFinalWidth * originalPlaneSvgHeight) / originalPlaneSvgWidth;
      let stationViewPlaneYItemFinalHeight = stationViewPlaneScaleHeight /25;
      let stationViewPlaneCoordYItems = this._document.getElementsByClassName('station-view-plane-coord-y')!; //Se obtienen las coordenadas en Y

      //Se iteran las coordenadas n Y para definir el alto de cada una
      for(let i = 0; i < stationViewPlaneCoordYItems.length; i++){
        let item = stationViewPlaneCoordYItems.item(i)! as HTMLElement;
        item.style.height = `${stationViewPlaneYItemFinalHeight}px`;
        item.style.width = `${stationViewPlaneYItemHeight}px`;
      }

      let firstXCoordInd = 0;
      let xCoords: string[] = [];
      for(let i = 0; i < numCoordXInt; i++){
        let firstXCoord = this.coords[firstXCoordInd];
        let secondXCoordInd = i % this.coords.length;
        let secondXCoord = this.coords[secondXCoordInd];
        let coord = `${firstXCoord}${secondXCoord}`;
        
        xCoords.push(coord);
        if(i % this.coords.length == this.coords.length - 1 && i > 0){
          firstXCoordInd++;
        }
      }

      this.stationLevelCoordsX = xCoords;
      setTimeout(() => {
        let stationViewPlaneCoordXItems = this._document.getElementsByClassName('station-view-plane-coord-x')!;
        for(let i = 0; i < stationViewPlaneCoordXItems.length; i++){
          let item = stationViewPlaneCoordXItems.item(i)! as HTMLElement;
          item.style.width = `${stationViewPlaneYItemHeight}px`;
          item.style.minWidth = `${stationViewPlaneYItemHeight}px`;
          item.style.height = `${stationViewPlaneYItemFinalHeight}px`;
          item.style.minHeight = `${stationViewPlaneYItemFinalHeight}px`;
        }

        let stationViewPlaneContainerStation = this._document.getElementById('station-view-plane-container-station')!;
        let stationViewPlaneX = this._document.getElementById('station-view-plane-x')!;

        stationViewPlaneContainerStation.addEventListener('wheel', (event: any) => {
          if(event.deltaY > 0){
            stationViewPlaneContainerStation.scrollLeft += 50;
            stationViewPlaneX.scrollLeft += 50;
            event.preventDefault();
          }else{
            stationViewPlaneContainerStation.scrollLeft -= 50;
            stationViewPlaneX.scrollLeft -= 50;
            event.preventDefault();
          }
        });
        
        stationViewPlaneContainerStation.addEventListener('scroll', (_: any) => {
          stationViewPlaneX.scrollLeft = stationViewPlaneContainerStation.scrollLeft;
        });

        let xPositionIndicators = this._document.getElementsByClassName('x_position_indicator')!;
        for(let i = 0; i < xPositionIndicators.length; i++){
          let item = xPositionIndicators.item(i)! as HTMLElement;
          item.style.width = `${stationViewPlaneYItemHeight}px`;
          item.style.minWidth = `${stationViewPlaneYItemHeight}px`;
        }

        let coordsY = this._document.getElementsByClassName('coords_y')!;
        for(let i = 0; i < coordsY.length; i++){
          let item = coordsY.item(i) as HTMLElement;
          item.style.height = `${stationViewPlaneYItemFinalHeight}px`;
          item.style.width = `${stationViewPlaneYItemHeight}px`;
        }

        this.showCoords = true;
        this.coordHeight = stationViewPlaneYItemFinalHeight;
        this.coordWidth = stationViewPlaneYItemHeight;
      }, 100);
    }, 100);
  }

  selectXCoordStationPlaneView(coord: string){
    if(this.selectedCoordX == ''){
      this.selectedCoordX = coord;
      setTimeout(() => {
        let yPositionIndicators = this._document.getElementsByClassName('y_position_indicator');
        for(let i = 0; i < yPositionIndicators.length; i++){
          let item = yPositionIndicators.item(i) as HTMLElement;
          item.style.height = `${this.coordHeight}px`;
          item.style.minHeight = `${this.coordHeight}px`;
          item.style.maxHeight = `${this.coordHeight}px`;
        }
      }, 100);
    }else{
      this.selectedCoordX = '';
      this.initPlaneView();
    }
  }

  openCoordsDetails(coordX: number, coordY: number){
    let familiesSelected: StationLevelsPlaneFamilies[] = [];
    let planeFilt = this.stationLevelsPlanes.filter(item => item.id == this.stationPlaneSelected);
    if(planeFilt.length > 0){
      familiesSelected = planeFilt[0].families;
    }
    
    let coordXStr = this.stationLevelCoordsX[coordX];
    let coordYStr = this.stationLevelCoordsY[coordY];
    let dialogRef = this._dialog.open(StationViewDetailedComponent, {
      width: '400px',
      minWidth: '400px',
      disableClose: true,
      data: {
        coordX: coordX,
        coordY: coordY,
        coordXStr: coordXStr,
        coordYStr: coordYStr,
        planeURL: this.stationPlaneSelectedURL,
        coordXTotal: this.stationLevelCoordsX.length,
        coordYTotal: this.stationLevelCoordsY.length,
        families: familiesSelected,
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res != null && res != undefined && res != ''){
        if(this.locatingCoords == 'S'){
          this.coordsLocated(res);
        }else{
          this.openStationEquipments(res);
        }
      }
    });
  }

  private async openStationEquipments(coords: string){
    let planeIDEnc = await this._encService.encrypt(`${this.stationPlaneSelected}`);
    let coordsEnc = await this._encService.encrypt(coords);
    let stationFilt = this.viaPositions[this.stationViewESVal!];
    
    this._dialog.open(StationLocationComponent, {
      width: '640px',
      maxWidth: '640px',
      data: {
        plane: planeIDEnc,
        coords: coordsEnc,
        station: stationFilt.name,
        level: this.stationViewLevel,
      },
    });
  }

  public onResize():void {
    if(this.locationType == 'ES' && this.stationViewESVal != undefined){
      this.initPlaneView();
    }else if(this.locationType == 'PC'){
      this.initPCCInterface();
    }
  }

  coordsLocated(coords: string){
    let dataObj = {
      idPlane: this.stationPlaneSelected,
      coords: coords,
    };

    let dataStr = JSON.stringify(dataObj);
    this.returnCoords.emit(dataStr);
  }

  coordBackground(coordY: string, coordX: string, isPCC: boolean = false): string{
    let planeCoord = `${coordY}${coordX}`;

    if(isPCC){
      let familiesFilt = this.pccFamilies.filter(family => family.originCoords == planeCoord);
      if(familiesFilt.length == 1){
        return familiesFilt[0].color;
      }else if(familiesFilt.length > 1){
        return "#E8559A";
      }
    }else{
      let planeSelected = this.stationLevelsPlanes.filter(item => item.id == this.stationPlaneSelected);
      if(planeSelected.length > 0){
        let familiesFilt = planeSelected[0].families.filter(family => (family.originCoords != null && family.originCoords.substring(0, 3) == planeCoord) || (family.destinyCoords != null && family.destinyCoords.substring(0, 3) == planeCoord));
        if(familiesFilt.length == 1){
          return familiesFilt[0].color;
        }else if(familiesFilt.length > 1){
          return "#E8559A";
        }
      }
    }

    return "transparent";
  }

  coordTooltip(coordY: string, coordX: string, isPCC: boolean = false): string{
    let planeCoord = `${coordY}${coordX}`;

    if(isPCC){
      let familiesFilt = this.pccFamilies.filter(family => family.originCoords == planeCoord);
      if(familiesFilt.length == 1){
        return familiesFilt[0].name;
      }else if(familiesFilt.length > 1){
        return `${familiesFilt.length} familias`;
      }
    }else{
      let planeSelected = this.stationLevelsPlanes.filter(item => item.id == this.stationPlaneSelected);
      if(planeSelected.length > 0){
        let familiesFilt = planeSelected[0].families.filter(family => (family.originCoords != null && family.originCoords.substring(0, 3) == planeCoord) || (family.destinyCoords != null && family.destinyCoords.substring(0, 3) == planeCoord));
        if(familiesFilt.length == 1){
          return familiesFilt[0].name;
        }else if(familiesFilt.length > 1){
          return `${familiesFilt.length} familias`;
        }
      }
    }
    
    return '';
  }

  carBackground(car: string): string{
    let familiesFilt = this.pccFamilies.filter(family => family.originCoords == car);
    if(familiesFilt.length == 1){
      return familiesFilt[0].color;
    }else if(familiesFilt.length > 1){
      return "#E8559A";
    }
    
    return "transparent";
  }

  carTooltip(car: string): string{
    let familiesFilt = this.pccFamilies.filter(family => family.originCoords == car);
    if(familiesFilt.length == 1){
      return familiesFilt[0].name;
    }else if(familiesFilt.length > 1){
      return `${familiesFilt.length} familias`;
    }
    
    return "";
  }

  viaBackground(startKM: string | number, endKM: string | number): string{
    let startKMNum: number = typeof startKM == 'string' ? parseFloat(startKM) : startKM;
    let endKMNum: number = typeof endKM == 'string' ? parseFloat(endKM) : endKM;
    let familiesFilt = this.pccFamilies.filter(family => (family.originKM! > endKMNum && family.originKM! <= startKMNum) || (family.destinyKM! > endKMNum && family.destinyKM! <= startKMNum));

    if(familiesFilt.length == 1){
      return familiesFilt[0].color;
    }else if(familiesFilt.length > 1){
      return "#E8559A";
    }
    
    return "transparent";
  }

  viaTooltip(startKM: string | number, endKM: string | number): string{
    let startKMNum: number = typeof startKM == 'string' ? parseFloat(startKM) : startKM;
    let endKMNum: number = typeof endKM == 'string' ? parseFloat(endKM) : endKM;
    let familiesFilt = this.pccFamilies.filter(family => (family.originKM! > endKMNum && family.originKM! <= startKMNum) || (family.destinyKM! > endKMNum && family.destinyKM! <= startKMNum));
    
    if(familiesFilt.length == 1){
      return familiesFilt[0].name;
    }else if(familiesFilt.length > 1){
      return `${familiesFilt.length} familias`;
    }
    
    return "";
  }
}
