using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Xml;
using ImageBlockz.Operations.InOut;
using ImageBlockz.Api;
using ImageBlockz.Core;
using AForge.Imaging.Filters;

namespace ImageBlockz.Operations.Filters
{
    public class ColorWeight : AbstractOperation
    {
        public static readonly string OperationName = typeof(ColorWeight).FullName;

        public ColorWeight()
            : base(OperationType.Filter)
        {
        
        }

        public ColorWeight(float red, float green, float blue)
            : this()
        {
            Red = red;
            Green = green;
            Blue = blue;
        }

        public float Red
        {
            set;
            get;
        }

        public float Green
        {
            set;
            get;
        }
        
        public float Blue
        {
            set;
            get;
        }

        public override Bitmap Do(Bitmap bmp)
        {
            Bitmap newBmp = new Bitmap(bmp.Width, bmp.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

            BitmapWrapper wrapperIn  = new BitmapWrapper(bmp);
            BitmapWrapper wrapperOut = new BitmapWrapper(newBmp);

            wrapperIn.Lock();
            wrapperOut.Lock();

            for (int i = 0; i < bmp.Width; i++)
                for (int j = 0; j < bmp.Height; j++)
                {
                    Color color = wrapperIn.GetPixel(i, j);
                    color = Color.FromArgb((int)(color.R * Red / 100.0), (int)(color.G * Green / 100.0), (int)(color.B * Blue / 100.0));
                    wrapperOut.SetPixel(color, i, j);
                }

            wrapperIn.Unlock();
            wrapperOut.Unlock();

            return newBmp;
        }

        public override XmlNode ToXml(XmlDocument xmlDoc)
        {
            XmlElement colorWeight = xmlDoc.CreateElement(OperationName);

            XmlElement red = XmlOperation.FloatToXml("red", Red, xmlDoc);
            XmlElement green = XmlOperation.FloatToXml("green", Green, xmlDoc);
            XmlElement blue = XmlOperation.FloatToXml("blue", Blue, xmlDoc);

            colorWeight.AppendChild(red);
            colorWeight.AppendChild(green);
            colorWeight.AppendChild(blue);

            return colorWeight;
        }

        public override void FromXml(XmlNode node)
        {
            Red   = XmlOperation.FloatFromXml(node["red"]);
            Green = XmlOperation.FloatFromXml(node["green"]);
            Blue  = XmlOperation.FloatFromXml(node["blue"]);        
        }

        public override string GetFormattedName()
        {
            return "Color Weight";
        }


        public override string GetInfo()
        {
            return "Red: " + Red + " Green: " + Green + " Blue: " + Blue;
        }
    }
}
