namespace CandyboxPlugin.Recipe
{
    public class ColorHeatMap
    {
        public ColorHeatMap()
        {
            initColorsBlocks();
        }

        public ColorHeatMap(byte alpha)
        {
            Alpha = alpha;
            initColorsBlocks();
        }

        private void initColorsBlocks()
        {
            ColorsOfMap.AddRange(new Color[]
            {
                Color.FromArgb(Alpha, Color.PaleVioletRed),
                Color.FromArgb(Alpha, Color.Yellow),
                Color.FromArgb(Alpha, Color.GreenYellow),
               
            });
        }

        public Color GetColorForValue(double val, double maxVal)
        {
            double valPerc = val / maxVal; // value%
            double colorPerc = 1d / (ColorsOfMap.Count-1); // % of each block of color. the last is the "100% Color"
            double blockOfColor = valPerc / colorPerc; // the integer part repersents how many block to skip
            int blockIdx = (int) Math.Truncate(blockOfColor); // Idx of 
            double valPercResidual = valPerc - blockIdx * colorPerc; //remove the part represented of block 
            double percOfColor = valPercResidual / colorPerc; // % of color of this block that will be filled

            Color cTarget = ColorsOfMap[blockIdx];
            if (blockIdx == ColorsOfMap.Count-1) return cTarget;
            Color cNext = cNext = ColorsOfMap[blockIdx + 1];

            var deltaR = cNext.R - cTarget.R;
            var deltaG = cNext.G - cTarget.G;
            var deltaB = cNext.B - cTarget.B;

            var R = cTarget.R + deltaR * valPercResidual;
            var G = cTarget.G + deltaG * valPercResidual;
            var B = cTarget.B + deltaB * valPercResidual;

            Color c = ColorsOfMap[0];
            try
            {
                c = Color.FromArgb(Alpha, (byte) R, (byte) G, (byte) B);
            }
            catch (Exception ex)
            {
            }

            return c;
        }

        public byte Alpha = 0xff;
        public List<Color> ColorsOfMap = new List<Color>();
    }
}