using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AForge.Controls;
using ImageBlockz.Operations;
using ImageBlockz.Operations.Edit;
using ImageBlockz.Api;
using ImageBlockz.Core;


namespace ImageBlockz.Operations.Controls
{
    public partial class ResizeControl : OperationControl
    {
        private ImageBlockz.Operations.Edit.Resize resize;

        public ResizeControl()
            : base(typeof(ImageBlockz.Operations.Edit.Resize).FullName)
        {
            IsPreview = false;
            Lock = false;

            InitializeComponent();

            
        }

        public override void SetOperation(IOperation operation)
        {
            base.SetOperation(operation);

            if (operation is ImageBlockz.Operations.Edit.Resize)
            {
                resize = (ImageBlockz.Operations.Edit.Resize) GetOperation();
            }
        }

        public bool Lock
        {
            get;
            set;
        }

        public override bool OnOK()
        {
            resize.SizeWH = new Size((int)dbWidth.GetValue(), (int)dbHeight.GetValue());

            return true;
        }

        public override void ShowData()
        {
            if (IsNew)
            {
                dbWidth.Value = 256;
                dbHeight.Value = 256;

                if (Bmp != null)
                {
                    dbWidth.Value = Bmp.Width;
                    dbHeight.Value = Bmp.Height;
                }
            }
            else
            {
                dbWidth.Value = resize.SizeWH.Width;
                dbHeight.Value = resize.SizeWH.Height;
            }

            if (Bmp == null)
            {
                Lock = false;
                button1.Visible = false;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (Lock == false)
            {
                button1.BackColor = Color.YellowGreen;
                Lock = true;
            }
            else
            {
                button1.BackColor = SystemColors.ButtonFace;
                Lock = false;
            }
        }

        private void dbWidth_Leave(object sender, EventArgs e)
        {
            WidthChanged();
        }

        private void dbHeight_Leave(object sender, EventArgs e)
        {
            HeightChanged();
        }

        private void WidthChanged()
        {
            if (Lock)
            {
                double ratio = (double)Bmp.Width / dbWidth.GetValue();
                dbHeight.Value = (int)(Bmp.Height / ratio);
            }
        }

        private void HeightChanged()
        {
            if (Lock)
            {
                double ratio = (double)Bmp.Height / dbHeight.GetValue();
                dbWidth.Value = (int)(Bmp.Width / ratio);

            }
        }
    }
}
