GtaVUsersInfo/MainForm.cs
2024-10-10 14:52:29 +03:00

670 lines
22 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using GtaVUsersInfo.Controls;
using GtaVUsersInfo.Forms;
using GtaVUsersInfo.Helpers;
using GtaVUsersInfo.Sources;
using Newtonsoft.Json;
using System.Data;
namespace GtaVUsersInfo
{
public partial class MainForm : Form
{
private List<Control> debugControlsList;
private List<Car> carList;
private List<ParameterControl> parameters;
private List<CarControl> cars;
private Font defaultFont;
private Color defaultColor;
private Color defaultPanelColor;
private List<Control> dtControls;
private FontSettings fontSettings;
private WindowParameters window;
private PanelColorSettings panelColorSettings;
private bool isUser;
public MainForm()
{
InitializeComponent();
defaultFont = new Font("Arial", 11, FontStyle.Regular);
defaultColor = Color.Black;
debugControlsList = new List<Control> { parserButton, readJsonButton };
this.visible(debugControlsList, false);
carList = LoadCarsFromJson(Resources.carJsonPath);
cars = new List<CarControl>();
parameters = new List<ParameterControl> { new ParameterControl("Имя"), new ParameterControl("Деньги") };
carsItems.ContextMenuStrip = new CarPanelMenuStrip(addCar_Click).Menu;
parametersPanel.ContextMenuStrip = new ParameterPanelMenuStrip(addNewParameter).Menu;
dtControls = new List<Control> { parserButton, readJsonButton };
fontSettings = FontSettings.LoadFontSettings();
if (fontSettings != null)
{
fontSettings.FontSettingsEdit(dtControls);
FontSettings.ChangeFontInControls(this, fontSettings);
}
else
{
fontSettings = new FontSettings(defaultFont, defaultColor, dtControls);
FontSettings.ChangeFontInControls(this, fontSettings);
FontSettings.SaveFontSettings(fontSettings);
}
isUser = false;
window = WindowParameters.LoadWindowParameters();
if (window != null)
{
if (window.prevFile != null)
{
Cars_Parameters lists = LoadDataFromFile(window.prevFile);
if (lists != null)
{
cars = lists.cars.Select(car => new CarControl(car)).ToList();
parameters = lists.parameters.Select(parameter => new ParameterControl(parameter)).ToList();
AllPanelCreate();
}
}
WindowResize();
}
else
{
window = new WindowParameters(new Size(this.Width, this.Height), new Size(this.splitterLeft.SplitPosition, this.splitterRigth.SplitPosition), IsFormFullscreen());
WindowParameters.SaveWindowParameters(window);
WindowResize();
}
panelColorSettings = PanelColorSettings.LoadPanelSettings();
if (panelColorSettings != null)
{
ChangePanelColor();
}
else
{
panelColorSettings = new PanelColorSettings(defaultPanelColor, defaultPanelColor, defaultPanelColor, defaultPanelColor);
ChangePanelColor();
}
isUser = true;
}
private bool IsFormFullscreen()
{
if (this.WindowState == FormWindowState.Maximized)
{
return true;
}
return false;
}
private void SetFullscreen(bool fullscreen)
{
if (fullscreen)
{
this.WindowState = FormWindowState.Maximized;
}
}
private void MainForm_Load(object sender, EventArgs e)
{
AllPanelCreate();
}
private void AllPanelCreate()
{
ParameterPanelCreate();
CarPanelCreate();
FontSettings.ChangeFontInControls(this, fontSettings);
}
private void WindowResize()
{
this.Width = window.width;
this.Height = window.height;
this.splitterLeft.SplitPosition = window.leftPos;
this.splitterRigth.SplitPosition = window.rightPos;
SetFullscreen(window.isFullScreen);
}
private void ParameterPanelCreate()
{
parametersPanel.Controls.Clear();
foreach (Control param in parameters)
{
param.Dock = DockStyle.Top;
(param as ParameterControl).MenuStrip = new ParameterItemMenuStrip(addNewParameter, deleteParameter, param as ParameterControl).Menu;
parametersPanel.Controls.Add(param);
parametersPanel.Controls.SetChildIndex(param, 0);
}
}
private void CarPanelCreate()
{
carsItems.Controls.Clear();
foreach (CarControl car in cars)
{
car.MenuStrip = new CarItemMenuStrip(addCar_Click, editCar, deleteCar, car.ChangeColor, car).Menu;
carsItems.Controls.Add(car);
}
}
public static List<Car> LoadCarsFromJson(string filePath)
{
try
{
string json = File.ReadAllText(filePath);
List<Car> cars = JsonConvert.DeserializeObject<List<Car>>(json);
return cars;
}
catch (FileNotFoundException)
{
ErrorsShow.ShowErrorMessage($"Файл с автомобилями не найден: {filePath}");
return new List<Car>();
}
catch (JsonException ex)
{
ErrorsShow.ShowErrorMessage($"Ошибка при десериализации JSON автомобилей: {ex.Message}");
return new List<Car>();
}
catch (Exception ex)
{
ErrorsShow.ShowErrorMessage($"Произошла неожиданная ошибка при открытии файла с автомобилями: {ex.Message}");
return new List<Car>();
}
}
#region Methods
private void visible(List<Control> controls, bool isVisible)
{
controls.ForEach(control => { control.Visible = isVisible; control.Enabled = isVisible; });
}
private void readJsonButton_Click(object sender, EventArgs e)
{
carList = LoadCarsFromJson(Resources.carJsonPath);
}
private void debugCheck_CheckedChanged(object sender, EventArgs e)
{
this.visible(debugControlsList, debugCheck.Checked);
}
#endregion
async private void parserButton_Click(object sender, EventArgs e)
{
using (var parser = new CarParser())
{
var cars = await parser.ParseCarsFromPages(25);
parser.SaveToJson(cars, Resources.carJsonPath);
ErrorsShow.ShowInfoMessage($"Данные сохранены: {Resources.carJsonPath}");
}
carList = LoadCarsFromJson(Resources.carJsonPath);
}
#region Методы автомобильной панели
private void addCar_Click(object sender, EventArgs e)
{
if (carList.Count <= 0)
{
ErrorsShow.ShowErrorMessage($"Список автомобилей пуст, ошибка чтения файла: {Resources.carJsonPath}");
return;
}
Car car = new Car();
using (AddCars form = new AddCars(carList, car))
{
form.ChangeFonts(fontSettings);
form.ShowDialog();
}
if (car.Name != null)
{
CarControl item = new CarControl(car);
cars.Add(item);
AllPanelCreate();
}
}
private void editCar(object sender, EventArgs e)
{
if (carList.Count <= 0)
{
ErrorsShow.ShowErrorMessage($"Список автомобилей пуст, ошибка чтения файла: {Resources.carJsonPath}");
return;
}
ToolStripMenuItem clickedMenuItem = sender as ToolStripMenuItem;
if (clickedMenuItem == null)
return;
CarItemMenuStrip menu = clickedMenuItem.Tag as CarItemMenuStrip;
if (menu == null)
return;
CarControl carItem = menu.Car;
if (carItem == null)
return;
Car car = new Car();
using (AddCars form = new AddCars(carList, car))
{
form.ShowDialog();
}
if (car.Name != null)
{
carItem.EditCar(car);
}
}
private void deleteCar(object sender, EventArgs e)
{
if (carList.Count <= 0)
{
ErrorsShow.ShowErrorMessage($"Список автомобилей пуст, ошибка чтения файла: {Resources.carJsonPath}");
return;
}
ToolStripMenuItem clickedMenuItem = sender as ToolStripMenuItem;
if (clickedMenuItem == null)
return;
CarItemMenuStrip menu = clickedMenuItem.Tag as CarItemMenuStrip;
if (menu == null)
return;
CarControl carItem = menu.Car;
if (carItem == null)
return;
if (cars.Contains(carItem))
{
DialogResult result = ErrorsShow.ShowQuestMessage(
$"Вы точно хотите удалить автомобиль: {carItem.Car.Name} - {carItem.Car.Price}?"
);
if (result == DialogResult.Yes)
{
cars.Remove(carItem);
AllPanelCreate();
}
if (result == DialogResult.Cancel)
{
return;
}
}
}
#endregion
#region Методы панели параметров
private void addParameter_Click(object sender, EventArgs e)
{
ParameterControl parameter = new ParameterControl();
using (AddParameter form = new AddParameter(parameters, parameter))
{
form.ChangeFonts(fontSettings);
form.ShowDialog();
}
if (!string.IsNullOrEmpty(parameter.ParamName))
{
parameter.Dock = DockStyle.Top;
parameters.Add(parameter);
AllPanelCreate();
}
}
private void addNewParameter(object sender, EventArgs e)
{
addParameter_Click(sender, e);
}
private void deleteParameter(object sender, EventArgs e)
{
if (parameters.Count <= 0)
{
ErrorsShow.ShowErrorMessage($"Список параметров пуст");
return;
}
ToolStripMenuItem clickedMenuItem = sender as ToolStripMenuItem;
if (clickedMenuItem == null)
return;
ParameterItemMenuStrip menu = clickedMenuItem.Tag as ParameterItemMenuStrip;
if (menu == null)
return;
ParameterControl parameterControl = menu.Parameter;
if (parameterControl == null)
return;
if (parameters.Contains(parameterControl))
{
DialogResult result = ErrorsShow.ShowQuestMessage(
$"Вы точно хотите удалить элемент: {parameterControl.ParamName}?"
);
if (result == DialogResult.Yes)
{
parameters.Remove(parameterControl);
AllPanelCreate();
}
if (result == DialogResult.Cancel)
{
return;
}
}
}
#endregion
#region Раскрывающийся список "Файл"
private void openFileToolStripMenuItem_Click(object sender, EventArgs e)
{
Cars_Parameters lists = LoadDataFromFile();
if (lists != null)
{
cars = lists.cars.Select(car => new CarControl(car)).ToList();
parameters = lists.parameters.Select(parameter => new ParameterControl(parameter)).ToList();
AllPanelCreate();
}
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveDataToFile("JSON files (*.json)|*.json|All files (*.*)|*.*");
AllPanelCreate();
}
private void saveAsКакToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveDataToFile("All files (*.*)|*.*");
}
public void SaveDataToFile(string filter)
{
Cars_Parameters data = new Cars_Parameters(Car.ConvertToCarList(cars), Parameter.ConvertToParameterList(parameters));
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = filter;
if (window.prevFile != null)
{
string jsonData = JsonConvert.SerializeObject(data, Formatting.Indented);
File.WriteAllText(window.prevFile, jsonData);
return;
}
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
// Сериализуем данные в JSON
string jsonData = JsonConvert.SerializeObject(data, Formatting.Indented);
// Записываем данные в файл
File.WriteAllText(saveFileDialog.FileName, jsonData);
}
}
public Cars_Parameters LoadDataFromFile()
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "JSON files (*.json)|*.json|All files (*.*)|*.*";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
// Читаем данные из файла
string jsonData = File.ReadAllText(openFileDialog.FileName);
// Десериализуем данные в объект ListData
Cars_Parameters data = JsonConvert.DeserializeObject<Cars_Parameters>(jsonData);
var split = openFileDialog.FileName.Split('\\');
this.Text = split[split.Length - 1];
window.prevFile = openFileDialog.FileName;
return data;
}
return null; // Если пользователь отменил выбор файла
}
public Cars_Parameters LoadDataFromFile(string filePath)
{
if (!File.Exists(filePath))
{
ErrorsShow.ShowErrorMessage($"Ошибка открытия файла: {filePath}");
return null;
}
// Читаем данные из файла
string jsonData = File.ReadAllText(filePath);
// Десериализуем данные в объект ListData
Cars_Parameters data = JsonConvert.DeserializeObject<Cars_Parameters>(jsonData);
var split = filePath.Split('\\');
this.Text = split[split.Length - 1];
return data;
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
DialogResult result = ErrorsShow.ShowQuestMessage("Хотите сохранить текущего персонажа?");
if (result == DialogResult.Yes)
{
SaveDataToFile("JSON files (*.json)|*.json|All files (*.*)|*.*");
}
if (result == DialogResult.Cancel)
{
return;
}
cars = new List<CarControl>();
parameters = new List<ParameterControl> { new ParameterControl("Имя"), new ParameterControl("Деньги") };
this.Text = "null";
window.prevFile = null;
AllPanelCreate();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult result = ErrorsShow.ShowQuestMessage("Хотите сохранить текущего персонажа?");
if (result == DialogResult.Yes)
{
SaveDataToFile("JSON files (*.json)|*.json|All files (*.*)|*.*");
}
if (result == DialogResult.Cancel)
{
e.Cancel = true;
return;
}
SaveWindowSize();
}
#endregion
#region Раскрывающийся список "Стили"
private void colorTextToolStripMenuItem_Click(object sender, EventArgs e)
{
using (ColorDialog colorDialog = new ColorDialog())
{
if (colorDialog.ShowDialog() == DialogResult.OK)
{
fontSettings.FontSettingsEdit(colorDialog.Color);
FontSettings.ChangeFontInControls(this, fontSettings);
FontSettings.SaveFontSettings(fontSettings);
}
}
}
private void styleTextToolStripMenuItem_Click(object sender, EventArgs e)
{
using (FontDialog fontDialog = new FontDialog())
{
if (fontDialog.ShowDialog() == DialogResult.OK)
{
fontSettings.FontSettingsEdit(fontDialog.Font);
FontSettings.ChangeFontInControls(this, fontSettings);
FontSettings.SaveFontSettings(fontSettings);
}
}
}
private void defaultToolStripMenuItem_Click(object sender, EventArgs e)
{
fontSettings.FontSettingsEdit(defaultFont);
fontSettings.FontSettingsEdit(defaultColor);
FontSettings.ChangeFontInControls(this, fontSettings);
FontSettings.SaveFontSettings(fontSettings);
}
#endregion
private void SaveWindowSize()
{
if (isUser)
{
window = new WindowParameters(new Size(this.Width, this.Height), new Size(this.splitterLeft.SplitPosition, this.splitterRigth.SplitPosition), IsFormFullscreen(), window.prevFile);
WindowParameters.SaveWindowParameters(window);
}
}
private void SaveColorPanel()
{
PanelColorSettings.SavePanelSettings(panelColorSettings);
}
private void ChangePanelColor()
{
this.buttonsPanel.BackColor = panelColorSettings.leftPanel;
PanelColorSettings.ChangeFontInControls(this.buttonsPanel, panelColorSettings.leftPanel);
this.parametersPanel.BackColor = panelColorSettings.rightPanel;
PanelColorSettings.ChangeFontInControls(this.parametersPanel, panelColorSettings.rightPanel);
this.carsPanel.BackColor = panelColorSettings.centerPanel;
this.carsItems.BackColor = panelColorSettings.centerPanel;
this.upPanel.BackColor = panelColorSettings.upDownPanel;
PanelColorSettings.ChangeFontInControls(this.upPanel, panelColorSettings.upDownPanel);
this.downPanel.BackColor = panelColorSettings.upDownPanel;
PanelColorSettings.ChangeFontInControls(this.downPanel, panelColorSettings.upDownPanel);
this.menuStrip.BackColor = panelColorSettings.upDownPanel;
this.splitterLeft.BackColor = panelColorSettings.upDownPanel;
this.splitterRigth.BackColor = panelColorSettings.upDownPanel;
}
private void buttonPanelToolStripMenuItem_Click(object sender, EventArgs e)
{
using (ColorDialog colorDialog = new ColorDialog())
{
if (colorDialog.ShowDialog() == DialogResult.OK)
{
panelColorSettings.leftPanel = colorDialog.Color;
ChangePanelColor();
SaveColorPanel();
}
}
}
private void parameterPanelToolStripMenuItem_Click(object sender, EventArgs e)
{
using (ColorDialog colorDialog = new ColorDialog())
{
if (colorDialog.ShowDialog() == DialogResult.OK)
{
panelColorSettings.rightPanel = colorDialog.Color;
ChangePanelColor();
SaveColorPanel();
}
}
}
private void carPanelToolStripMenuItem_Click(object sender, EventArgs e)
{
using (ColorDialog colorDialog = new ColorDialog())
{
if (colorDialog.ShowDialog() == DialogResult.OK)
{
panelColorSettings.centerPanel = colorDialog.Color;
ChangePanelColor();
SaveColorPanel();
}
}
}
private void top_downPanelToolStripMenuItem_Click(object sender, EventArgs e)
{
using (ColorDialog colorDialog = new ColorDialog())
{
if (colorDialog.ShowDialog() == DialogResult.OK)
{
panelColorSettings.upDownPanel = colorDialog.Color;
ChangePanelColor();
SaveColorPanel();
}
}
}
}
}