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 VisiMath;
using VisimBox;
using System.Xml.Serialization;

namespace VisimBuilder
{
    public partial class VectorEditing : UserControl
    {
        public delegate void VectorChangedCallback(VectorEditing sender, Vector3 newvalue);

        public event VectorChangedCallback VectorChanged;
        
        private Vector3 Vector;
        
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Vector3 EditedVector
        {
            get
            {
                return Vector;
            }

            set
            {
                Vector = value;
                UpdateFromVector();
            }
        }
        
        public VectorEditing()
        {
            InitializeComponent();
            UpdateFromVector();
        }

        void UpdateFromVector()
        {
            textBoxVector.Text = string.Format("{0} : {1} : {2}",
                Vector.X.ToString("F"), Vector.Y.ToString("F"), Vector.Z.ToString("F"));
        }

        void UpdateFromEditor()
        {
            Vector3 vec = ParseString(textBoxVector.Text);
            if (vec.IsValid())
            {
                Vector = vec;
                if (VectorChanged != null)
                    VectorChanged(this, vec);
            }
        }

        public Vector3 ParseString(string str)
        {
            StringParser parser = new StringParser(str, ':');
            if (parser.WordCount != 3)
                return Vector3.Invalid;
            if (!parser.IsFloat(0) || !parser.IsFloat(1) || !parser.IsFloat(2))
                return Vector3.Invalid;

            return new Vector3(parser.GetFloat(0), parser.GetFloat(1), parser.GetFloat(2));
        }

        private void TextBoxKeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                UpdateFromEditor();
                e.Handled = true;
            }
        }

        private void FocusLeave(object sender, EventArgs e)
        {
            UpdateFromEditor();
        }

    }
}
