#ifndef _HCM4AMobServ_h
#define _HCM4AMobServ_h

#include <CtrlLib/CtrlLib.h>
#include <GridCtrl/GridCtrl.h>
using namespace Upp;

#define IMAGECLASS Images
#define IMAGEFILE <HCM4AMobileService/icons.iml>
#include <Draw/iml.h>

#define LAYOUTFILE <HCM4AMobileService/MobileService.lay>
#include <CtrlCore/lay.h>
#include "GisMap.h"
#include "GisObjects.h"
#include "Common.h"

// Application version constant
const String APP_VERSION = "1.20";

// Constants for distance validation in calculations
const int AcceptedMaxCalculateDistanceKm = 999;
const int AcceptedMinCalculateDistanceKm = 200;

/**
 * Dialog for managing stations tab layout and functionality
 */
struct StationsTabDlg : WithStationsLayout<ParentCtrl> {
	StationsTabDlg();
};

/**
 * Dialog for managing maps tab with GIS functionality and display options
 */
struct MapsTabDlg : WithMapsLayout<ParentCtrl> {
public:
	GisMap map;
	StatusBar statusBar;
	InfoCtrl infoLongLati, infoZoom, infoTopo, infoMorpho, infoDop;
	Option showTopoTile, showMorphoTile, showDegLines;

	MapsTabDlg();
	
	/**
	 * Updates map display options based on user selections
	 */
	void ChangeOptions();
};

/**
 * Dialog for testing stations functionality
 */
struct StationsTestDlg : WithStationsTestLayout<ParentCtrl> {
	StationsTestDlg();
};

/**
 * Dialog for displaying point-to-point calculation results
 */
struct ResultsLayoutDlgP2p : WithResultsLayoutP2p<ParentCtrl> {
	ResultsLayoutDlgP2p();
};

/**
 * Dialog for displaying line calculation results
 */
struct ResultsLayoutDlgLine : WithResultsLayoutLine<ParentCtrl> {
	ResultsLayoutDlgLine();
};

/**
 * Dialog for displaying CBR (Carrier-to-Broadcast Ratio) calculation results
 */
struct ResultsLayoutDlgCbr : WithResultsLayoutCBR<ParentCtrl> {
	ResultsLayoutDlgCbr();
};

/**
 * Dialog for displaying combined results from multiple calculation types
 */
struct ResultLayoutDlgCombine : WithResultLayoutCombine<ParentCtrl> {
	ResultLayoutDlgCombine();
};

/**
 * Configuration structure for mobile service application settings
 * Contains paths, file extensions, and application preferences
 */
struct MobileServiceSettings {
	String PathToTopo = "";              // Path to topographic data
	String PathToMorpho = "";            // Path to morphological data  
	String PathToBorders = "";           // Path to border data
	int MaxCalcDistance = 0;             // Maximum calculation distance
	String FileWithCountriesCodes = "";  // File containing country codes
	String ExtensionsForRecordSave = "Station Txt format (*.txt)\t*.txt\nStation JSON format(*.json) \t*.json\nStation Excel (*.xlsx)\t*.xlsx";
	String ExtensionsForRecordLoad = "Station in TXT, JSON, Excel formats (*.txt; *.json; *.xlsx)\t*.txt; *.json; *.xlsx\n";
	String LastPathForOpeningDialog = ""; // Last used path for file dialogs

	/**
	 * Saves settings to persistent storage
	 */
	void Save();
	
	/**
	 * Loads settings from persistent storage
	 */
	void Load();
};

/**
 * Represents a mobile station with geographical and technical parameters
 */
struct MobileStation {
	String Name = "";
	double Longitude, Latitude = 0;      // Geographical coordinates
	double FreqTx, FreqRx, Azimut, Heigth, Radius = 0;  // Technical parameters
	bool isRefList;                       // Flag indicating if station is in reference list
	String Filename = "";                 // Source filename
	String Land = "";                     // Country/land information
	int IndexInFile = 0;                  // Index position in source file
};

/**
 * Represents a line feature on the map with multiple points
 */
struct LineOnMap {
	String Name = "";                     // Line identifier
	Vector<Pointf> Points;               // Sequence of points defining the line
	Color LineColor = LtBlue();          // Display color for the line
};

/**
 * Main application class for Mobile Service functionality
 * Handles station management, calculations, and result display
 */
class MobileService : public WithMobileServiceLayout<TopWindow> {
public:

	// Custom tab coloring for UI
	Color customActiveTabBg = Color(100, 180, 255);
	Color customInactiveTabBg = SColorFace();
	Color customActiveTabText = White();
	Color customInactiveTabText = SColorText();

	/**
	 * Recursively searches for files matching specified pattern in directory
	 * @param directory - Path to search directory
	 * @param mask - File pattern mask to match
	 * @param result - Output array for found file paths
	 */
	void FindFiles(const String& directory, const String& mask, Array<String>& result);

	/**
	 * Structure for storing map coordinate information
	 */
	struct mapCoord {
		int id;                          // Coordinate identifier
		double longitude;                // Longitude value
		double latitude;                 // Latitude value  
		int zoom;                        // Zoom level for display
	};

	Vector<mapCoord> mapTreeCoordArray;  // Collection of map coordinates
	Vector<String> debugFiles;           // Files used for debugging
	bool flagP2pCalcDone = false, flagLineCalcDone = false, flagCbrCalcDone = false; // Calculation status flags

	String pathRef, pathTest;            // Paths for reference and test stations
	Array<String> ListRefStationFiles, ListTestStationFiles; // Station file lists
	Array<MobileStation> StationsList;   // Collection of loaded stations
	Array<LineOnMap> LinesOnMap;         // Collection of lines displayed on map

	String OpenedFileName = "";          // Currently opened filename
	int indexOpenedStation = -1;         // Index of currently opened station

	/**
	 * Updates the list of stations in the UI
	 */
	void RefreshListOfStations();
	
	/**
	 * Updates combined results layout with current image data
	 */
	void UpdateImageResultsCombineLayout();
	
	/**
	 * Updates combined results with station file data
	 * @return true if update successful, false otherwise
	 */
	bool UpdateResCombineStationFileData();
	
	/**
	 * Loads station data from file
	 * @return true if load successful, false otherwise
	 */
	bool LoadeStationFileData();
	
	/**
	 * Loads country codes data if available
	 */
	void CheckAndLoadCountriesCodes();

	/**
	 * Reads station data from UI controls
	 * @return Formatted station data string
	 */
	String ReadStationFromControls();
	
	/**
	 * Reads station header information from UI controls
	 * @return Formatted header string
	 */
	String ReadStationHeaderFromControls();

	/**
	 * Saves station data to file
	 * @param index - Index of station to save
	 */
	void StationSaveToFile(int index);
	
	/**
	 * Loads header information into UI
	 */
	void LoadHeader();
	
	/**
	 * Loads station data into UI
	 * @param index - Index of station to load
	 */
	void LoadStation(int index);
	
	/**
	 * Clears header controls in UI
	 */
	void ClearHeaderControls();
	
	/**
	 * Clears station data controls in UI
	 */
	void ClearStationControls();
	
	/**
	 * Deletes station from file
	 * @param index - Index of station to delete
	 */
	void StationDeleteFromFile(int index);

	// UI components
	TabCtrl mainTab;
	StationsTabDlg tabStations;
	StationsTestDlg tabStationsTest;
	ResultsLayoutDlgP2p tabResP2p;
	ResultsLayoutDlgLine tabResLine;
	ResultsLayoutDlgCbr tabResCbr;
	ResultLayoutDlgCombine tabResCombine;
	MapsTabDlg tabMap;

	Font fnt;                            // Application font
	Color textColor;                     // Text color scheme

	WithSettingsLayout<TopWindow> SettingsLO; // Settings layout
	FileSel fsLoadStations;              // File selector for loading stations
	FileSel fsSaveStations;              // File selector for saving stations  
	FileSel faSettings;                  // File selector for settings
	MobileServiceSettings cnfg;          // Application configuration
	TabCtrl::Style s = TabCtrl::StyleDefault(); // Tab control style
	MenuBar menu;                        // Main application menu

	FileDataJs ResultResponceData;       // Result data storage

	/**
	 * Builds main application menu
	 * @param bar - Menu bar to populate
	 */
	void MainMenu(Bar& bar);
	
	/**
	 * Displays about application dialog
	 */
	void AboutApp();
	
	/**
	 * Reads station data from file
	 * @param filename - Path to station file
	 * @param index - Station index in file
	 * @param isRefList - Flag indicating reference station
	 */
	void ReadFileWithStation(String filename, int index, bool isRefList);
	
	/**
	 * Refreshes settings display in UI
	 */
	void RefreshSettings();
	
	/**
	 * Prepares settings for application use
	 */
	void PrepareSettings();
	
	/**
	 * Refreshes map tree structure
	 */
	void RefreshMapTree();
	
	/**
	 * Prepares map tree for display
	 */
	void PrepareMapTree();
	
	/**
	 * Refreshes stations lists in UI
	 */
	void RefreshStationsLists();
	
	/**
	 * Prepares stations lists for use
	 */
	void PrepareStationsLists();
	
	/**
	 * Reads all station files into memory
	 */
	void ReadAllFileStations();
	
	/**
	 * Prepares all result layouts for display
	 */
	void PrepareResultLayouts();
	
	/**
	 * Prepares line result layout specifically
	 */
	void PrepareResultLayoutLine();
	
	/**
	 * Prepares point-to-point result layout specifically
	 */
	void PrepareResultLayoutP2p();
	
	/**
	 * Prepares CBR result layout specifically
	 */
	void PrepareResultLayoutCbr();
	
	/**
	 * Prepares combined result layout specifically
	 */
	void PrepareResultLayoutCombine();
	
	/**
	 * Performs point-to-point calculation
	 */
	void CalculationP2p();
	
	/**
	 * Performs line calculation
	 */
	void CalculationLine();
	
	/**
	 * Performs CBR calculation
	 */
	void CalculationCbr();

	/**
	 * Clears point-to-point result table
	 */
	void ClearResultTableP2p();
	
	/**
	 * Clears line result table
	 */
	void ClearResultTableLine();
	
	/**
	 * Clears CBR result table
	 */
	void ClearResultTableCbr();
	
	/**
	 * Clears combined result table
	 */
	void ClearResultTableCombine();
	
	/**
	 * Clears all result tables
	 */
	void ClearResultTablesAll();

	WithStationEditorLayout<TopWindow> StationEditor; // Station editor dialog

	/**
	 * Sets station editor to default values
	 */
	void SetStationDefault();
	
	/**
	 * Clears station editor controls
	 */
	void SetStationClear();
	
	/**
	 * Prepares station editor for use
	 */
	void PrepareStationEditor();
	
	/**
	 * Loads station data into editor
	 * @param filename - Source filename
	 * @param index - Station index
	 * @return true if load successful, false otherwise
	 */
	bool LoadStationToEditor(String filename, int index);
	
	/**
	 * Parses station string and populates editor controls
	 * @param source - Station data string
	 * @param numStation - Station number
	 * @return true if parsing successful, false otherwise
	 */
	bool StationStringToControls(String source, int numStation);
	
	/**
	 * Parses header string and populates editor controls
	 * @param source - Header data string
	 * @return true if parsing successful, false otherwise
	 */
	bool HeaderStringToControls(String source);
	
	/**
	 * Saves station editor data to file
	 * @param filename - Target filename
	 * @return true if save successful, false otherwise
	 */
	bool SaveStationEditorToFile(String filename);
	
	/**
	 * Validates station editor data
	 * @return true if data valid, false otherwise
	 */
	bool ValidateStationEditor();
	
	/**
	 * Generates new station filename
	 * @param iReferenceStation - Flag for reference station type
	 * @return Generated filename
	 */
	String GetNewStationFileName(bool iReferenceStation);
	
	/**
	 * Displays station editor dialog
	 * @param mode - Editor mode (create/edit/etc)
	 * @param index - Station index for editing
	 */
	void ShowStationEditor(int mode, int index = 0);

	/**
	 * Handles application close event
	 */
	void Close();
	
	/**
	 * Constructor - initializes mobile service application
	 */
	MobileService();
};

#endif