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;

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

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

        public RadiusCrop(Point center, int radius)
            : this()
        {
            Center = center;
            Radius = radius;
        }

        public Point Center
        {
            get;
            set;
        }
        
        public int Radius
        {
            get;
            set;
        }

       
        public override Bitmap Do(Bitmap img)
        {
            try
            {
                Rectangle rect = new Rectangle(Center.X - Radius, Center.Y - Radius, Radius * 2, Radius * 2);

                Bitmap cropedBmp = img.Clone(rect, img.PixelFormat);
                return cropedBmp;
            }
            catch
            {
                System.Windows.Forms.MessageBox.Show("Illegal values for cropping. Correct your entry. Operartion will be skiped for now.");    
            }

            return img;
        }

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

            XmlElement centerX = XmlOperation.FloatToXml("x", Center.X, xmlDoc);
            XmlElement centerY = XmlOperation.FloatToXml("y", Center.Y, xmlDoc);

            XmlElement radius = XmlOperation.FloatToXml("radius", Radius, xmlDoc);

            radiuscrop.AppendChild(centerX);
            radiuscrop.AppendChild(centerY);
            radiuscrop.AppendChild(radius);

            return radiuscrop;
        }

        public override void FromXml(XmlNode node)
        {
            Radius = (int) XmlOperation.FloatFromXml(node["radius"]);

            Point point = new Point((int) XmlOperation.FloatFromXml(node["x"]), (int) XmlOperation.FloatFromXml(node["y"]));

            Center = point;
        }

        public override string GetFormattedName()
        {
            return "Crop with Radius";
        }


        public override string GetInfo()
        {
            return "Center X: " + Center.X.ToString() + " Center Y: " + Center.Y.ToString() + " Radius: " + Radius.ToString();
        }
    }
}
