using System;
using System.IO;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Writer
{
    public partial class MainForm : Form
    {
        private static readonly HttpClient http = new HttpClient();
        private static readonly string ServerUrl;

        static MainForm()
        {
            var configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "appsettings.json");
            var jsonContent = System.IO.File.ReadAllText(configPath);
            var start = jsonContent.IndexOf('"', jsonContent.IndexOf("ServerUrl") + 10);
            var end = jsonContent.IndexOf('"', start + 1);
            ServerUrl = jsonContent.Substring(start + 1, end - start - 1).Trim();
        }

        public MainForm()
        {
            InitializeComponent();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            using var ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                txtFile.Text = ofd.FileName;
            }
        }

        private async void btnWrite_Click(object sender, EventArgs e)
        {
            var file = txtFile.Text;
            if (string.IsNullOrWhiteSpace(file) || !File.Exists(file))
            {
                MessageBox.Show("请选择有效的文件。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            var upload = txtUpload.Text ?? string.Empty;
            var download = txtDownload.Text ?? string.Empty;
            try
            {
                var sha = await Task.Run(() => ComputeSha256(file));
                var payload = new { sha = sha, upload_code = upload, download_code = download };
                var content = new StringContent(JsonSerializer.Serialize(payload), Encoding.UTF8, "application/json");
                var resp = await http.PostAsync(ServerUrl + "/write", content);
                if (resp.IsSuccessStatusCode)
                {
                    MessageBox.Show("写入暗码成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("写入失败: " + await resp.Content.ReadAsStringAsync(), "失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("发生错误: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private static string ComputeSha256(string filePath)
        {
            using var sha = SHA256.Create();
            using var stream = File.OpenRead(filePath);
            var hash = sha.ComputeHash(stream);
            var sb = new StringBuilder();
            foreach (var b in hash) sb.Append(b.ToString("x2"));
            return sb.ToString();
        }
    }
}
