using System;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;
using Minio;
using Minio.DataModel;
using Minio.Exceptions;
using test2;
using static System.Net.Mime.MediaTypeNames;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace TestMinio
{
    public partial class Form1 : Form
    {
        static  string  endpoint = "10.40.18.12:9000";
        static string accessKey = "root";
        static string secretKey = "root_password";
        // Initialize the client with access credentials.
        private static MinioClient minio = new MinioClient()
                                            .WithEndpoint(endpoint)
                                            .WithCredentials(accessKey, secretKey)
                                            .Build();

        // Create an async task for listing buckets.
       
        public Form1()
        {
            InitializeComponent();
        }


        private async void button1_Click(object sender, EventArgs e)
        {
            // Create an async task for listing buckets.
            var getListBucketsTask = await minio.ListBucketsAsync().ConfigureAwait(true);

            // Iterate over the list of buckets.
            foreach (var bucket in getListBucketsTask.Buckets)
            {
                Console.WriteLine($"{bucket.Name} {bucket.CreationDateDateTime} \n");
            }

            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                // 设置文件对话框的标题
                openFileDialog.Title = "选择要上传的文件";

                // 设置文件对话框允许选择的文件类型（例如：图片、文本文件等）
                openFileDialog.Filter = "All Files (*.*)|*.*";

                // 设置是否允许选择多个文件
                openFileDialog.Multiselect = false;

                // 打开文件对话框，并等待用户选择文件
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    // 获取选择的文件路径并显示在 TextBox 中
                    label1.Text = openFileDialog.FileName;
                   // Run(openFileDialog.FileName);
                    await MinioFileManager.UploadFileAsync(openFileDialog.FileName);
                    loadBucket();
                }
            }
        }

        private async  Task<String> Run(String filePath)
        {
            var bucketName = $"hbl";
            var objectName = System.IO.Path.GetFileName(filePath);
            var contentType = "application/zip";

            try
            {
                // Make a bucket on the server, if not already present.
                var beArgs = new BucketExistsArgs()
                    .WithBucket(bucketName);
                bool found = await minio.BucketExistsAsync(beArgs).ConfigureAwait(false);
                if (!found)
                {
                    var mbArgs = new MakeBucketArgs()
                        .WithBucket(bucketName);
                    await minio.MakeBucketAsync(mbArgs).ConfigureAwait(false);
                }
                // Upload a file to bucket.
                var putObjectArgs = new PutObjectArgs()
                    .WithBucket(bucketName)
                    .WithObject($"{DateTime.Now.ToString("yyyy-MM-dd")}/{objectName}")
                    .WithFileName(filePath);
                await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false);
                Console.WriteLine("Successfully uploaded " + objectName);
                var url =$"http://{endpoint}/hbl/{DateTime.Now.ToString("yyyy-MM-dd")}/{objectName}";
                MessageBox.Show(url);
                Console.WriteLine(url);
                return url;
            }
            catch (MinioException e)
            {
                Console.WriteLine("File Upload Error: {0}", e.Message);
            }
            return $"上传失败";
        }

        private async void button2_Click(object sender, EventArgs e)
        {
             var val=  getNodeVal();
             if (val == null) return;
             await MinioFileManager.DownloadFileAsync(val);
             MessageBox.Show("下载成功");
        }

        private string getNodeVal() {
            //await  MinioFileManager.DownloadFileAsync("2023-08-10/200406113500-7.jpg");
            TreeNode selectedNode = treeView.SelectedNode;
            if (selectedNode != null)
            {
                if (selectedNode.Nodes.Count == 0)
                {
                    // 选定的是叶子节点，拼接完整文件路径
                    string fullPath = GetFullPath(selectedNode);
                    return fullPath;
                   // MessageBox.Show("选定的叶子节点的完整路径：" + fullPath, "完整文件路径", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    // 选定的不是叶子节点，清除选定节点
                    treeView.SelectedNode = null;
                    MessageBox.Show("没有选定节点！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else
            {
                MessageBox.Show("没有选定节点！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            return null;
        }
        private string GetFullPath(TreeNode node)
        {
            string fullPath = node.Text;
            TreeNode parentNode = node.Parent;
            while (parentNode != null)
            {
                fullPath = $"{parentNode.Text}/{fullPath}";
                parentNode = parentNode.Parent;
            }
            return fullPath;
        }
        private void loadBucket() {
            treeView.Nodes.Clear();
            MinioFileManager.ListObjects(item => {
                //textBox1.Invoke(new Action(() => textBox1.Text += $"{item.Key}\n"));
                //textBox1.Text += $"{item.Key}\n"; 
                treeView.Invoke(new Action(() => PopulateTreeView(item.Key)));
            });
        }

        private void PopulateTreeView(String filePath)
        {
            string[] pathSegments = filePath.Split('/');

            TreeNode currentNode = null;
            TreeNodeCollection nodes = treeView.Nodes;

            foreach (string segment in pathSegments)
            {
                TreeNode[] matchingNodes = nodes.Find(segment, false);

                if (matchingNodes.Length > 0)
                {
                    currentNode = matchingNodes[0];
                }
                else
                {
                    currentNode = nodes.Add(segment, segment);
                }

                nodes = currentNode.Nodes;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            loadBucket();
        }

        private async void button3_Click(object sender, EventArgs e)
        {
            var val = getNodeVal();
            if (val == null) return;
            await MinioFileManager.DeleteFileAsync(val);
            MessageBox.Show("删除成功");
            loadBucket();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            loadBucket();
        }
    }
}
