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 VisimBox.Renderer;

namespace VisimBuilder
{
    public partial class TextureLookup : UserControl
    {
        public TextureLookup()
        {
            InitializeComponent();
        }

        string _selTexture;
        Bitmap BMP;

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public string SelectedTexture
        {
            get
            {
                return _selTexture;
            }

            set
            {
                if (DesignMode)
                    return;
                if (BMP != null)
                    BMP.Dispose();
                _selTexture = value;
                var texman = VisimBox.VisimEngine.Instance.Renderer.TextureMan;
                if ((texman != null) && (_selTexture != null) && (texman.Contains(_selTexture)))
                {
                    Texture tex = texman[_selTexture];
                    BMP = tex.GetBitmap();
                    pictureBox1.Image = BMP;
                }
                else
                    pictureBox1.Load("Textures/NoTexture.png");
            }
        }

        private void buttonFromDisk_Click(object sender, EventArgs e)
        {
            if (openFileDialogTexture.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string filen = VisimBox.FileSystem.Instance.GetRelativePath(openFileDialogTexture.FileName);
                Texture tex = VisimBox.VisimEngine.Instance.Renderer.TextureMan.Load(filen);
                if (tex == null)
                {
                    MessageBox.Show("Texture loading failed!");
                    return;
                }

                UpdateTextureCombo();
                comboBoxTextures.SelectedItem = filen;
            }            
        }

        private void TexChanged(object sender, EventArgs e)
        {
            SelectedTexture = (string)comboBoxTextures.SelectedItem;
        }

        protected void UpdateTextureCombo()
        {
            var texman = VisimBox.VisimEngine.Instance.Renderer.TextureMan;
            comboBoxTextures.Items.Clear();

            foreach (var tex in texman)
            {
                comboBoxTextures.Items.Add(tex.Value.Name);
            }
            comboBoxTextures.SelectedItem = _selTexture;
        }

        private void buttonRefresh_Click(object sender, EventArgs e)
        {
            UpdateTextureCombo();
        }

    }
}
