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 CtbSimpleCliffTexture : Contribution {
        protected static Dictionary<Color, SimpleCliffPlateSet> registerdSet = new Dictionary<Color, SimpleCliffPlateSet>();
        protected static string CacheDirRoot;
        public readonly Color BaseColor;
        protected SimpleCliffPlateSet plateSet;

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

        //protected override InitCompleteEventHandler Initialize() {
        //    return null;
        //}

        //public ITexture GetTexture(Scaler scl, CliffPolygon poly, Point3DV hint) {
        //    return imgSet.GetTexture(scl, poly, hint);
        //}

        public ICliffPlateSet TextureSet {
            get { return plateSet; }
        }

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

    public class SimpleCliffPlateSet : CliffPlateSet<UInt32>
    {
        public readonly Color BaseColor;
        protected readonly Contribution owner;
        internal protected SimpleCliffPlateSet(Contribution c, Color basecol) {
            this.BaseColor = basecol;
            this.owner = c;
        }

        protected override uint ToHashKey(CliffPolygon polygon, int height, Point3DV hint) {
            return (UInt32)polygon.ID + ((UInt32)height<<16);
        }

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

        protected override bool IsHeightOver(KeyValuePair<UInt32, TemplateHolder> pair, int height) {
            UInt32 h = (UInt32)height << 16;
            return pair.Key > h;
        }
    }
}
