using System;
using System.Collections.Generic;
using System.Text;
using nft.framework.plugin;
using nft.framework.drawing;
using System.Xml;
using nft.util;
using nft.framework;
using System.Drawing;
using System.IO;
using nft.core;

namespace nft.contributions.graphics
{
    public class CtbImageResource : Contribution
    {
        protected IImageSrc source;
        protected WeakReference reffer;
        protected Color colorkey;
        protected bool auto_color_key;
        protected string src_text;

        public CtbImageResource(Plugin owner, XmlElement contrib) :base(owner, contrib,
            "file:"+XmlUtil.GetSingleNodeText(contrib, "src", "<unknwon>"), "")
        {
            reffer = null;
            XmlNode nd = contrib.SelectSingleNode("src");
            src_text = nd.InnerText;
            string attext = XmlUtil.GetAttribute(nd, "colorkey", null);
            auto_color_key = attext==null;
            if (auto_color_key)
            {
                colorkey = Color.Transparent;
            }
            else
            {
                colorkey = StringParseUtil.CreateColor(attext);
            }
            
        }

        protected string SrcText
        {
            // 'name' holds inner text of <src> element.
            get { return src_text; }
        }

        public string FilePath
        {
            get{ return Path.Combine(PluginDir, SrcText); }
        }

        public IImageSrc ImageSrc
        {
            get
            {
                if (reffer != null && reffer.IsAlive) {
                    return (IImageSrc)reffer.Target;
                } else {
                    // Image file might be shared by contributions in the same plugin. So assign plugin key.
                    ResourceKey key = ResourceKey.CreateKey(Parent, SrcText);
                    IImageSrc img;
                    if (auto_color_key) {
                        // use left-bottom pixel as color-key
                        img = GraphicManagerEx.GraphicManager.LoadImageFromFileWithDefaultColorKey(key, FilePath);
                    } else {
                        img = GraphicManagerEx.GraphicManager.LoadImageFromFile(key, FilePath, colorkey);
                    }
                    reffer = new WeakReference(img);
                    return img;
                }
            }
        }
    }
}
