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

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

        public Resize()
            : base(OperationType.Filter)
        {

        }

        public Resize(Size size) 
            : this()
        {
            SizeWH = size;
        }

        public Size SizeWH
        {
            get;
            set;
        }

        public override Bitmap Do(Bitmap bmp)
        {
            int bmpWidth  = bmp.Width; 
            int bmpHeight = bmp.Height;

            /*
            float nPercent  = 0;
            float nPercentW = 0;
            float nPercentH = 0;

            nPercentW = ((float)SizeWH.Width  / (float)bmpWidth);
            nPercentH = ((float)SizeWH.Height / (float)bmpHeight);

            if (nPercentH < nPercentW)
                nPercent = nPercentH;
            else
                nPercent = nPercentW;
            

            int newWidth  = (int)(bmpWidth * nPercent);
            int newHeight = (int)(bmpHeight * nPercent);

            */

            int newWidth = (int)(SizeWH.Width);
            int newHeight = (int)(SizeWH.Height);

            PixelFormat format = PixelFormat.Format24bppRgb;

            Bitmap resizedImage = new Bitmap(newWidth, newHeight, format);
            Graphics graphic = Graphics.FromImage((Image)resizedImage);

            graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

            graphic.DrawImage(bmp, 0, 0, newWidth, newHeight);
            graphic.Dispose();

            return resizedImage;   
        }

        public override XmlNode ToXml(XmlDocument xmlDoc)
        {
            XmlElement resize = xmlDoc.CreateElement(OperationName);
            XmlElement size = XmlOperation.SizeToXml(SizeWH, xmlDoc);

            resize.AppendChild(size);

            return resize;
        }

        public override void FromXml(XmlNode node)
        {
            SizeWH = XmlOperation.SizeFromXml(node["size"]);
        }

        public override string GetFormattedName()
        {
            return "Resize";
        }

        public override string GetInfo()
        {
            return "Width: " + SizeWH.Width + ", Height: " + SizeWH.Height;
        }
    }
}
