RecipeInfoForm.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776
  1. using System;
  2. using System.IO;
  3. using System.Windows.Forms;
  4. namespace Server.Database
  5. {
  6. public partial class RecipeInfoForm : Form
  7. {
  8. private string currentFilePath;
  9. private bool isModified = false;
  10. private bool _ignoreItemSelectionEvent = false;
  11. public RecipeInfoForm()
  12. {
  13. InitializeComponent();
  14. this.Load += RecipeInfoForm_Load;
  15. SaveButton.Click += SaveButton_Click;
  16. }
  17. #region Form Load
  18. private void RecipeInfoForm_Load(object sender, EventArgs e)
  19. {
  20. // Define the directory path where the recipes are stored
  21. string currentDirectory = AppDomain.CurrentDomain.BaseDirectory;
  22. string directoryPath = Path.Combine(currentDirectory, "Envir", "Recipe");
  23. // Clear the selected item in the ItemComboBox on load
  24. ItemComboBox.SelectedIndex = -1; // No item selected initially
  25. // Check if the directory exists
  26. if (Directory.Exists(directoryPath))
  27. {
  28. // Get all recipe files (with .txt extension) from the directory
  29. string[] recipeFiles = Directory.GetFiles(directoryPath, "*.txt");
  30. // Clear existing items in the RecipeList (if any)
  31. RecipeList.Items.Clear();
  32. // Add recipe filenames to the RecipeList
  33. foreach (string recipeFile in recipeFiles)
  34. {
  35. // Get the filename without the extension
  36. string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(recipeFile);
  37. RecipeList.Items.Add(fileNameWithoutExtension);
  38. }
  39. }
  40. else
  41. {
  42. MessageBox.Show("The recipe directory does not exist.", "Directory Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  43. }
  44. LoadItemsIntoComboBox();
  45. UpdateRecipeCount();
  46. }
  47. #endregion
  48. #region Recipe Count
  49. private void UpdateRecipeCount()
  50. {
  51. // Define the directory path where the recipes are stored
  52. string currentDirectory = AppDomain.CurrentDomain.BaseDirectory;
  53. string directoryPath = Path.Combine(currentDirectory, "Envir", "Recipe");
  54. int recipeCount = 0;
  55. // Check if the directory exists
  56. if (Directory.Exists(directoryPath))
  57. {
  58. // Count all recipe files with a .txt extension
  59. string[] recipeFiles = Directory.GetFiles(directoryPath, "*.txt");
  60. recipeCount = recipeFiles.Length;
  61. }
  62. // Update the RecipeCountLabel with the total count
  63. RecipeCountLabel.Text = $"Recipe Count: {recipeCount}";
  64. }
  65. #endregion
  66. #region Recipe List Index Changed
  67. private void RecipeList_SelectedIndexChanged(object sender, EventArgs e)
  68. {
  69. if (RecipeList.SelectedIndex == -1)
  70. return;
  71. // Get the selected recipe file name
  72. string selectedRecipeName = RecipeList.SelectedItem.ToString();
  73. LoadRecipe(selectedRecipeName);
  74. }
  75. #endregion
  76. #region Clear Recipe
  77. private void ClearRecipeForm()
  78. {
  79. // Clear Craft Amount, Chance, and Gold fields
  80. CraftAmountTextBox.Text = string.Empty;
  81. ChanceTextBox.Text = string.Empty;
  82. GoldTextBox.Text = string.Empty;
  83. // Clear Ingredient Name ComboBoxes
  84. IngredientName1ComboBox.SelectedIndex = -1;
  85. IngredientName2ComboBox.SelectedIndex = -1;
  86. IngredientName3ComboBox.SelectedIndex = -1;
  87. IngredientName4ComboBox.SelectedIndex = -1;
  88. IngredientName5ComboBox.SelectedIndex = -1;
  89. IngredientName6ComboBox.SelectedIndex = -1;
  90. // Clear Ingredient Amount and Durability TextBoxes
  91. IngredientAmount1TextBox.Text = string.Empty;
  92. IngredientAmount2TextBox.Text = string.Empty;
  93. IngredientAmount3TextBox.Text = string.Empty;
  94. IngredientAmount4TextBox.Text = string.Empty;
  95. IngredientAmount5TextBox.Text = string.Empty;
  96. IngredientAmount6TextBox.Text = string.Empty;
  97. IngredientDura1TextBox.Text = string.Empty;
  98. IngredientDura2TextBox.Text = string.Empty;
  99. IngredientDura3TextBox.Text = string.Empty;
  100. IngredientDura4TextBox.Text = string.Empty;
  101. IngredientDura5TextBox.Text = string.Empty;
  102. IngredientDura6TextBox.Text = string.Empty;
  103. }
  104. #endregion
  105. #region Load Recipes
  106. private void LoadRecipe(string recipeName)
  107. {
  108. string currentDirectory = AppDomain.CurrentDomain.BaseDirectory;
  109. string directoryPath = Path.Combine(currentDirectory, "Envir", "Recipe");
  110. string filePath = Path.Combine(directoryPath, recipeName + ".txt");
  111. // Check if the file exists
  112. if (File.Exists(filePath))
  113. {
  114. // Read the lines from the recipe file and parse as needed
  115. string[] fileLines = File.ReadAllLines(filePath);
  116. ParseAndDisplayRecipe(fileLines);
  117. // Temporarily ignore the combo box event while we select the item
  118. _ignoreItemSelectionEvent = true;
  119. try
  120. {
  121. SetItemComboBoxSelection(recipeName);
  122. }
  123. finally
  124. {
  125. _ignoreItemSelectionEvent = false;
  126. }
  127. // Set isModified to true since the recipe was loaded and might be changed
  128. isModified = true;
  129. currentFilePath = filePath; // Store the current file path for later rename operations
  130. }
  131. else
  132. {
  133. MessageBox.Show("The selected recipe file does not exist.", "File Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  134. }
  135. }
  136. #endregion
  137. #region Item Combo Box
  138. private void SetItemComboBoxSelection(string recipeName)
  139. {
  140. // Look for an item name matching the recipe
  141. foreach (var item in SMain.EditEnvir.ItemInfoList)
  142. {
  143. if (item.Name.Equals(recipeName, StringComparison.OrdinalIgnoreCase))
  144. {
  145. // Programmatically set the ComboBox
  146. ItemComboBox.SelectedItem = item.Name;
  147. break;
  148. }
  149. }
  150. }
  151. #endregion
  152. #region Parse Recipe
  153. private void ParseAndDisplayRecipe(string[] fileLines)
  154. {
  155. // Initialise default values
  156. string amount = "";
  157. string chance = "";
  158. string gold = "";
  159. // Tool data
  160. string[] tools = new string[3];
  161. // Ingredient data
  162. string[] ingredientNames = new string[6];
  163. string[] ingredientAmounts = new string[6];
  164. string[] ingredientDurabilities = new string[6];
  165. // Flags to track current section
  166. bool inToolsSection = false;
  167. bool inIngredientsSection = false;
  168. int toolIndex = 0;
  169. int ingredientIndex = 0;
  170. foreach (string line in fileLines)
  171. {
  172. // Skip empty lines
  173. if (string.IsNullOrWhiteSpace(line)) continue;
  174. // Detect [Recipe] section (skip header)
  175. if (line.StartsWith("[Recipe]"))
  176. {
  177. inToolsSection = false;
  178. inIngredientsSection = false;
  179. continue;
  180. }
  181. // Parse key-value pairs for [Recipe] section
  182. if (line.StartsWith("Amount ") || line.StartsWith("Chance ") || line.StartsWith("Gold "))
  183. {
  184. string[] parts = line.Split(new[] { ' ' }, 2);
  185. if (parts.Length == 2)
  186. {
  187. string key = parts[0].Trim();
  188. string value = parts[1].Trim();
  189. if (key == "Amount") amount = value;
  190. else if (key == "Chance") chance = value;
  191. else if (key == "Gold") gold = value;
  192. }
  193. continue;
  194. }
  195. // Detect [Tools] section
  196. if (line.StartsWith("[Tools]"))
  197. {
  198. inToolsSection = true;
  199. inIngredientsSection = false;
  200. continue;
  201. }
  202. // Detect [Ingredients] section
  203. if (line.StartsWith("[Ingredients]"))
  204. {
  205. inToolsSection = false;
  206. inIngredientsSection = true;
  207. continue;
  208. }
  209. // Parse tools (only in [Tools] section)
  210. if (inToolsSection && toolIndex < 3)
  211. {
  212. tools[toolIndex++] = line.Trim();
  213. continue;
  214. }
  215. // Parse ingredients (only in [Ingredients] section)
  216. if (inIngredientsSection && ingredientIndex < 6)
  217. {
  218. string[] ingredientParts = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  219. if (ingredientParts.Length >= 1)
  220. {
  221. ingredientNames[ingredientIndex] = ingredientParts[0].Trim();
  222. if (ingredientParts.Length >= 2)
  223. ingredientAmounts[ingredientIndex] = ingredientParts[1].Trim();
  224. if (ingredientParts.Length == 3)
  225. ingredientDurabilities[ingredientIndex] = ingredientParts[2].Trim();
  226. ingredientIndex++;
  227. }
  228. }
  229. }
  230. // Update text boxes with parsed values
  231. CraftAmountTextBox.Text = amount;
  232. ChanceTextBox.Text = chance;
  233. GoldTextBox.Text = gold;
  234. // Populate tool ComboBoxes
  235. PopulateToolComboBox(Tool1ComboBox, tools[0]);
  236. PopulateToolComboBox(Tool2ComboBox, tools[1]);
  237. PopulateToolComboBox(Tool3ComboBox, tools[2]);
  238. // Populate ingredient ComboBoxes
  239. PopulateIngredientComboBox(IngredientName1ComboBox, ingredientNames[0]);
  240. PopulateIngredientComboBox(IngredientName2ComboBox, ingredientNames[1]);
  241. PopulateIngredientComboBox(IngredientName3ComboBox, ingredientNames[2]);
  242. PopulateIngredientComboBox(IngredientName4ComboBox, ingredientNames[3]);
  243. PopulateIngredientComboBox(IngredientName5ComboBox, ingredientNames[4]);
  244. PopulateIngredientComboBox(IngredientName6ComboBox, ingredientNames[5]);
  245. // Populate ingredient amount and durability text boxes
  246. IngredientAmount1TextBox.Text = ingredientAmounts[0];
  247. IngredientAmount2TextBox.Text = ingredientAmounts[1];
  248. IngredientAmount3TextBox.Text = ingredientAmounts[2];
  249. IngredientAmount4TextBox.Text = ingredientAmounts[3];
  250. IngredientAmount5TextBox.Text = ingredientAmounts[4];
  251. IngredientAmount6TextBox.Text = ingredientAmounts[5];
  252. IngredientDura1TextBox.Text = ingredientDurabilities[0];
  253. IngredientDura2TextBox.Text = ingredientDurabilities[1];
  254. IngredientDura3TextBox.Text = ingredientDurabilities[2];
  255. IngredientDura4TextBox.Text = ingredientDurabilities[3];
  256. IngredientDura5TextBox.Text = ingredientDurabilities[4];
  257. IngredientDura6TextBox.Text = ingredientDurabilities[5];
  258. }
  259. #endregion
  260. #region Populate Tools
  261. private void PopulateToolComboBox(ComboBox toolComboBox, string toolName)
  262. {
  263. // Clear the ComboBox before adding new items
  264. toolComboBox.Items.Clear();
  265. // Add "None" as the first item
  266. toolComboBox.Items.Add("None");
  267. // Add items from the item database
  268. foreach (var item in SMain.EditEnvir.ItemInfoList)
  269. {
  270. if (!string.IsNullOrEmpty(item.Name))
  271. {
  272. toolComboBox.Items.Add(item.Name);
  273. }
  274. }
  275. // Set the selected item if the tool name is valid
  276. if (!string.IsNullOrEmpty(toolName))
  277. {
  278. toolComboBox.SelectedItem = toolName;
  279. }
  280. else
  281. {
  282. toolComboBox.SelectedIndex = 0; // Default to "None"
  283. }
  284. }
  285. #endregion
  286. #region Populate Ingredients
  287. private void PopulateIngredientComboBox(ComboBox comboBox, string ingredientName)
  288. {
  289. comboBox.Items.Clear(); // Clear the ComboBox first
  290. // Add "None" as the first item
  291. comboBox.Items.Add("None");
  292. // Ensure ItemInfoList is populated
  293. if (SMain.EditEnvir.ItemInfoList != null && SMain.EditEnvir.ItemInfoList.Count > 0)
  294. {
  295. // Add item names to the ComboBox
  296. foreach (var item in SMain.EditEnvir.ItemInfoList)
  297. {
  298. if (!string.IsNullOrEmpty(item.Name))
  299. {
  300. comboBox.Items.Add(item.Name);
  301. }
  302. }
  303. // Set the selected item to the ingredient name (if it exists in the list)
  304. if (!string.IsNullOrEmpty(ingredientName) && comboBox.Items.Contains(ingredientName))
  305. {
  306. comboBox.SelectedItem = ingredientName;
  307. }
  308. else
  309. {
  310. comboBox.SelectedIndex = 0; // Default to "None"
  311. }
  312. }
  313. else
  314. {
  315. MessageBox.Show("No items found in the ItemInfoList.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  316. }
  317. }
  318. #endregion
  319. #region Load Items
  320. private void LoadItemsIntoComboBox()
  321. {
  322. // Ensure ItemInfoList is populated
  323. if (SMain.EditEnvir.ItemInfoList != null && SMain.EditEnvir.ItemInfoList.Count > 0)
  324. {
  325. ItemComboBox.Items.Clear();
  326. // Loop through ItemInfoList and add item names to the combo box
  327. foreach (var item in SMain.EditEnvir.ItemInfoList)
  328. {
  329. if (!string.IsNullOrEmpty(item.Name))
  330. {
  331. ItemComboBox.Items.Add(item.Name);
  332. }
  333. }
  334. // Optionally set the first item as selected if the ComboBox is not empty
  335. if (ItemComboBox.Items.Count > 0)
  336. {
  337. ItemComboBox.SelectedIndex = -1; // No item selected initially
  338. }
  339. }
  340. else
  341. {
  342. MessageBox.Show("No items found in the ItemInfoList.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  343. }
  344. }
  345. #endregion
  346. #region Save Recipe
  347. private void SaveRecipe()
  348. {
  349. if (string.IsNullOrEmpty(currentFilePath)) return;
  350. try
  351. {
  352. using (StreamWriter writer = new StreamWriter(currentFilePath))
  353. {
  354. // Write [Recipe] section
  355. writer.WriteLine("[Recipe]");
  356. writer.WriteLine($"Amount {CraftAmountTextBox.Text}");
  357. writer.WriteLine($"Chance {ChanceTextBox.Text}");
  358. writer.WriteLine($"Gold {GoldTextBox.Text}");
  359. writer.WriteLine();
  360. writer.WriteLine("[Tools]");
  361. // Write tools, skipping None
  362. if (Tool1ComboBox.SelectedItem.ToString() != "None")
  363. writer.WriteLine(Tool1ComboBox.SelectedItem.ToString());
  364. if (Tool2ComboBox.SelectedItem.ToString() != "None")
  365. writer.WriteLine(Tool2ComboBox.SelectedItem.ToString());
  366. if (Tool3ComboBox.SelectedItem.ToString() != "None")
  367. writer.WriteLine(Tool3ComboBox.SelectedItem.ToString());
  368. writer.WriteLine();
  369. writer.WriteLine("[Ingredients]");
  370. // Write ingredients, skipping None
  371. WriteIngredient(writer, IngredientName1ComboBox, IngredientAmount1TextBox, IngredientDura1TextBox);
  372. WriteIngredient(writer, IngredientName2ComboBox, IngredientAmount2TextBox, IngredientDura2TextBox);
  373. WriteIngredient(writer, IngredientName3ComboBox, IngredientAmount3TextBox, IngredientDura3TextBox);
  374. WriteIngredient(writer, IngredientName4ComboBox, IngredientAmount4TextBox, IngredientDura4TextBox);
  375. WriteIngredient(writer, IngredientName5ComboBox, IngredientAmount5TextBox, IngredientDura5TextBox);
  376. WriteIngredient(writer, IngredientName6ComboBox, IngredientAmount6TextBox, IngredientDura6TextBox);
  377. }
  378. MessageBox.Show("Recipe saved successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
  379. isModified = false;
  380. }
  381. catch (Exception ex)
  382. {
  383. MessageBox.Show($"Error saving recipe: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  384. }
  385. }
  386. private void WriteIngredient(StreamWriter writer, ComboBox nameComboBox, TextBox amountTextBox, TextBox duraTextBox)
  387. {
  388. if (nameComboBox.SelectedItem.ToString() == "None") return; // Skip if None is selected
  389. string name = nameComboBox.SelectedItem.ToString();
  390. string amount = string.IsNullOrWhiteSpace(amountTextBox.Text) ? "" : amountTextBox.Text;
  391. string dura = string.IsNullOrWhiteSpace(duraTextBox.Text) ? "" : duraTextBox.Text;
  392. // Write ingredient line with optional amount and durability
  393. writer.WriteLine($"{name} {amount} {dura}".Trim());
  394. }
  395. #endregion
  396. #region Form Close
  397. private void RecipeInfoForm_FormClosing(object sender, FormClosingEventArgs e)
  398. {
  399. // Prompt to save only if isModified is true
  400. if (isModified)
  401. {
  402. // You could prompt before auto-saving, but here we'll just save
  403. SaveRecipe();
  404. }
  405. }
  406. #endregion
  407. #region New Recipe Button
  408. private void NewRecipeButton_Click(object sender, EventArgs e)
  409. {
  410. // Define the directory path where the recipes are stored
  411. string currentDirectory = AppDomain.CurrentDomain.BaseDirectory;
  412. string directoryPath = Path.Combine(currentDirectory, "Envir", "Recipe");
  413. // Ensure the directory exists
  414. if (!Directory.Exists(directoryPath))
  415. {
  416. MessageBox.Show("The recipe directory does not exist.", "Directory Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  417. return;
  418. }
  419. // Generate a unique file name for the new recipe
  420. string newRecipeName = "NewRecipe";
  421. string newRecipePath = Path.Combine(directoryPath, $"{newRecipeName}.txt");
  422. int counter = 1;
  423. // Avoid overwriting existing files by appending a number to the name if needed
  424. while (File.Exists(newRecipePath))
  425. {
  426. newRecipeName = $"NewRecipe{counter}";
  427. newRecipePath = Path.Combine(directoryPath, $"{newRecipeName}.txt");
  428. counter++;
  429. }
  430. // Create a blank recipe file with the specified layout
  431. try
  432. {
  433. using (StreamWriter writer = new StreamWriter(newRecipePath))
  434. {
  435. writer.WriteLine("[Recipe]");
  436. writer.WriteLine("Amount ");
  437. writer.WriteLine("Chance ");
  438. writer.WriteLine("Gold ");
  439. writer.WriteLine();
  440. writer.WriteLine("[Tools]");
  441. writer.WriteLine();
  442. writer.WriteLine("[Ingredients]");
  443. }
  444. }
  445. catch (Exception ex)
  446. {
  447. MessageBox.Show($"Failed to create the new recipe file. Error: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  448. return;
  449. }
  450. // Update the form to display the new recipe
  451. RecipeList.Items.Add(newRecipeName);
  452. RecipeList.SelectedItem = newRecipeName; // Automatically select the new recipe
  453. // Reset all combo boxes and text boxes to their default values
  454. ItemComboBox.SelectedIndex = 0; // "None"
  455. CraftAmountTextBox.Text = string.Empty;
  456. ChanceTextBox.Text = string.Empty;
  457. GoldTextBox.Text = string.Empty;
  458. Tool1ComboBox.SelectedIndex = 0; // "None"
  459. Tool2ComboBox.SelectedIndex = 0; // "None"
  460. Tool3ComboBox.SelectedIndex = 0; // "None"
  461. IngredientName1ComboBox.SelectedIndex = 0; // "None"
  462. IngredientName2ComboBox.SelectedIndex = 0; // "None"
  463. IngredientName3ComboBox.SelectedIndex = 0; // "None"
  464. IngredientName4ComboBox.SelectedIndex = 0; // "None"
  465. IngredientName5ComboBox.SelectedIndex = 0; // "None"
  466. IngredientName6ComboBox.SelectedIndex = 0; // "None"
  467. IngredientAmount1TextBox.Text = string.Empty;
  468. IngredientAmount2TextBox.Text = string.Empty;
  469. IngredientAmount3TextBox.Text = string.Empty;
  470. IngredientAmount4TextBox.Text = string.Empty;
  471. IngredientAmount5TextBox.Text = string.Empty;
  472. IngredientAmount6TextBox.Text = string.Empty;
  473. IngredientDura1TextBox.Text = string.Empty;
  474. IngredientDura2TextBox.Text = string.Empty;
  475. IngredientDura3TextBox.Text = string.Empty;
  476. IngredientDura4TextBox.Text = string.Empty;
  477. IngredientDura5TextBox.Text = string.Empty;
  478. IngredientDura6TextBox.Text = string.Empty;
  479. // Update the current file path and set the modified flag
  480. currentFilePath = newRecipePath;
  481. isModified = true;
  482. MessageBox.Show($"New recipe created: {newRecipeName}.txt", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
  483. UpdateRecipeCount();
  484. }
  485. #endregion
  486. #region Item Combo Box Index Change Event
  487. private void ItemComboBox_SelectedIndexChanged(object sender, EventArgs e)
  488. {
  489. // If we're currently ignoring this event (because we're loading), do nothing
  490. if (_ignoreItemSelectionEvent) return;
  491. // If there's no file loaded, do nothing
  492. if (string.IsNullOrEmpty(currentFilePath)) return;
  493. string selectedItemName = ItemComboBox.SelectedItem?.ToString();
  494. if (string.IsNullOrEmpty(selectedItemName)) return;
  495. // Compare old vs new
  496. string oldRecipeName = Path.GetFileNameWithoutExtension(currentFilePath);
  497. string oldTrimmed = oldRecipeName.Trim();
  498. string newTrimmed = selectedItemName.Trim();
  499. // If the name is effectively the same, skip
  500. if (oldTrimmed.Equals(newTrimmed, StringComparison.OrdinalIgnoreCase))
  501. {
  502. return;
  503. }
  504. // Otherwise rename
  505. UpdateRecipeFileName(selectedItemName);
  506. // Update the list item if something was actually renamed
  507. if (RecipeList.SelectedIndex >= 0)
  508. {
  509. RecipeList.Items[RecipeList.SelectedIndex] = selectedItemName;
  510. }
  511. isModified = true;
  512. }
  513. #endregion
  514. #region Update Recipe File Name
  515. private void UpdateRecipeFileName(string newItemName)
  516. {
  517. string directoryPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Envir", "Recipe");
  518. string newFilePath = Path.Combine(directoryPath, newItemName + ".txt");
  519. // If both paths match (ignoring case), skip the rename
  520. if (currentFilePath.Equals(newFilePath, StringComparison.OrdinalIgnoreCase))
  521. return;
  522. // If a different file with that new name already exists, warn and skip
  523. if (File.Exists(newFilePath))
  524. {
  525. MessageBox.Show(
  526. $"A recipe named '{newItemName}' already exists. Cannot rename.",
  527. "Rename Error",
  528. MessageBoxButtons.OK,
  529. MessageBoxIcon.Warning
  530. );
  531. return;
  532. }
  533. // Rename the existing file
  534. if (File.Exists(currentFilePath))
  535. {
  536. try
  537. {
  538. File.Move(currentFilePath, newFilePath);
  539. currentFilePath = newFilePath;
  540. }
  541. catch (Exception ex)
  542. {
  543. MessageBox.Show($"Error renaming recipe file: {ex.Message}",
  544. "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  545. }
  546. }
  547. }
  548. #endregion
  549. #region Open Recipe Button
  550. private void OpenRecipeButton_Click(object sender, EventArgs e)
  551. {
  552. // Check if a recipe has been selected from the RecipeList
  553. if (RecipeList.SelectedIndex == -1)
  554. {
  555. MessageBox.Show("Please select a recipe from the list.", "No Recipe Selected", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  556. return;
  557. }
  558. // Get the selected recipe file name
  559. string selectedRecipeName = RecipeList.SelectedItem.ToString();
  560. string currentDirectory = AppDomain.CurrentDomain.BaseDirectory;
  561. string directoryPath = Path.Combine(currentDirectory, "Envir", "Recipe");
  562. string filePath = Path.Combine(directoryPath, selectedRecipeName + ".txt");
  563. // Check if the recipe file exists
  564. if (File.Exists(filePath))
  565. {
  566. try
  567. {
  568. // Use Process.Start with the file path
  569. System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
  570. {
  571. FileName = filePath,
  572. UseShellExecute = true // Use the default system shell to open
  573. });
  574. }
  575. catch (Exception ex)
  576. {
  577. MessageBox.Show($"Error opening file: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  578. }
  579. }
  580. else
  581. {
  582. MessageBox.Show("The selected recipe file does not exist.", "File Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  583. }
  584. }
  585. #endregion
  586. #region Save Button
  587. private void SaveButton_Click(object sender, EventArgs e)
  588. {
  589. SaveRecipe();
  590. }
  591. #endregion
  592. #region Delete Button
  593. private void DeleteButton_Click(object sender, EventArgs e)
  594. {
  595. // Check if a recipe is selected
  596. if (RecipeList.SelectedIndex == -1)
  597. {
  598. MessageBox.Show("Please select a recipe to delete.", "No Recipe Selected", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  599. return;
  600. }
  601. // Get the selected recipe name
  602. string selectedRecipeName = RecipeList.SelectedItem.ToString();
  603. string currentDirectory = AppDomain.CurrentDomain.BaseDirectory;
  604. string directoryPath = Path.Combine(currentDirectory, "Envir", "Recipe");
  605. string filePath = Path.Combine(directoryPath, $"{selectedRecipeName}.txt");
  606. // Confirm deletion
  607. var result = MessageBox.Show(
  608. $"Are you sure you want to delete the recipe: {selectedRecipeName}?",
  609. "Confirm Deletion",
  610. MessageBoxButtons.YesNo,
  611. MessageBoxIcon.Question
  612. );
  613. if (result != DialogResult.Yes) return;
  614. // Delete the file
  615. try
  616. {
  617. if (File.Exists(filePath))
  618. {
  619. File.Delete(filePath);
  620. RecipeList.Items.Remove(selectedRecipeName); // Remove from the list
  621. MessageBox.Show($"Recipe deleted: {selectedRecipeName}.txt", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
  622. // Clear the form and reset controls
  623. ClearForm();
  624. }
  625. else
  626. {
  627. MessageBox.Show("The selected recipe file does not exist.", "File Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  628. }
  629. }
  630. catch (Exception ex)
  631. {
  632. MessageBox.Show($"Failed to delete the recipe file. Error: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  633. }
  634. // Update the recipe count
  635. UpdateRecipeCount();
  636. }
  637. // Clears the form fields
  638. private void ClearForm()
  639. {
  640. RecipeList.SelectedIndex = -1; // No recipe selected
  641. ItemComboBox.SelectedIndex = 0; // Reset to "None"
  642. CraftAmountTextBox.Text = string.Empty;
  643. ChanceTextBox.Text = string.Empty;
  644. GoldTextBox.Text = string.Empty;
  645. Tool1ComboBox.SelectedIndex = 0; // Reset to "None"
  646. Tool2ComboBox.SelectedIndex = 0;
  647. Tool3ComboBox.SelectedIndex = 0;
  648. IngredientName1ComboBox.SelectedIndex = 0; // Reset to "None"
  649. IngredientName2ComboBox.SelectedIndex = 0;
  650. IngredientName3ComboBox.SelectedIndex = 0;
  651. IngredientName4ComboBox.SelectedIndex = 0;
  652. IngredientName5ComboBox.SelectedIndex = 0;
  653. IngredientName6ComboBox.SelectedIndex = 0;
  654. IngredientAmount1TextBox.Text = string.Empty;
  655. IngredientAmount2TextBox.Text = string.Empty;
  656. IngredientAmount3TextBox.Text = string.Empty;
  657. IngredientAmount4TextBox.Text = string.Empty;
  658. IngredientAmount5TextBox.Text = string.Empty;
  659. IngredientAmount6TextBox.Text = string.Empty;
  660. IngredientDura1TextBox.Text = string.Empty;
  661. IngredientDura2TextBox.Text = string.Empty;
  662. IngredientDura3TextBox.Text = string.Empty;
  663. IngredientDura4TextBox.Text = string.Empty;
  664. IngredientDura5TextBox.Text = string.Empty;
  665. IngredientDura6TextBox.Text = string.Empty;
  666. }
  667. #endregion
  668. }
  669. }