using BitMiracle.LibTiff.Classic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Channels;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace XPrint.Image
{
    // 定义通道名称映射类
    [XmlRoot("ChannelNames")]
    public class ChannelNameMapping
    {
        [XmlElement("Channel")]
        public List<Channel> Channels { get; set; } = null!;
    }

    public class Channel
    {
        [XmlAttribute("Index")]
        public int Index { get; set; }
        [XmlAttribute("Name")]
        public string Name { get; set; } = null!;
    }

    public class TiffModifier
    {
        public static void RenameCustomChannels(string inputPath, string outputPath, Dictionary<int, string> channelNames)
        {
            using (Tiff tiff = Tiff.Open(inputPath, "r+"))
            {
                if (tiff == null) throw new IOException("无法打开TIFF文件");

                // 遍历所有IFD，修改首IFD的ImageDescription标签
                tiff.SetDirectory(0); // 仅修改首IFD的元数据
                var xmlSerializer = new XmlSerializer(typeof(ChannelNameMapping));


                tiff.ReadEXIFDirectory(0);

                // 构建XML元数据
                var mapping = new ChannelNameMapping
                {
                    Channels = new List<Channel>()
                };
                foreach (var kvp in channelNames)
                {
                    mapping.Channels.Add(new Channel { Index = kvp.Key, Name = kvp.Value });
                }

                using (StringWriter writer = new StringWriter())
                {
                    xmlSerializer.Serialize(writer, mapping);
                    string xmlData = writer.ToString();

                    // 写入ImageDescription标签（0x010E）
                    tiff.SetField(TiffTag.IMAGEDESCRIPTION, xmlData);
                }

                // 保存修改
                tiff.WriteDirectory();
            }

            // 覆盖原文件
            File.Copy(inputPath, outputPath, true);
        }
    }
}
