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

namespace nft.contributions.terrain {
    public class CtbSimpleGroundTexture : Contribution {
        protected static Dictionary<Color, SimpleGroundPlateSet> registerdSet = new Dictionary<Color,SimpleGroundPlateSet>();
        protected static string CacheDirRoot;
        public readonly Color BaseColor;
        protected SimpleGroundPlateSet plateSet;

        public CtbSimpleGroundTexture(Plugin p, CtbGroundTextureFactory factory, ParamsReader ctb)
            : base(p, ctb) {
            string text = ctb["basecolor"].InnerText;
            BaseColor = ColorUtil.To12BitColor(StringParseUtil.CreateColor(text));
            CreateAndRegister(this, BaseColor, out plateSet);
        }

        public IGroundPlateSet TerrainPlateSet {
            get { return plateSet; }
        }

        protected static bool CreateAndRegister(Contribution owner, Color basecol, out SimpleGroundPlateSet gpSet) {
            if (registerdSet.ContainsKey(basecol)) {
                gpSet = registerdSet[basecol];
                return false; // already registerd
            }
            gpSet = new SimpleGroundPlateSet(owner, basecol);
            registerdSet.Add(basecol, gpSet);
            return true;
        }

    }

    public class SimpleGroundPlateSet : TerrainPlateSet<ushort, GroundPolygon>, IGroundPlateSet
    {
        public readonly Color BaseColor;
        protected readonly Contribution owner;
        internal protected SimpleGroundPlateSet(Contribution c, Color basecol) {
            this.BaseColor = basecol;
            this.owner = c;
        }

        protected override ITerrainPlateTemplate CreateTemplate(GroundPolygon polygon, Point3DV hint) {
            Point3D[] v = polygon.GetVerticis3D();
            ITerrainPlateTemplate templ = null;
            ResourceKey rkey = ResourceKey.CreateKey(owner, ToHashKey(polygon, hint));
            templ = GraphicManager.CreateTerrainTemplate(rkey, BaseColor, v, polygon.Brightness);
            return templ;
        }

        protected override ushort ToHashKey(GroundPolygon polygon, Point3DV hint) {
            return polygon.ID;
        }
    }

}
