using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using ComponentFramework;
using MTV3D65;

namespace FullScreenShaders.Forms
{
    partial class SettingsChooser : Form
    {
        readonly List<TV_MODEFORMAT> modes = new List<TV_MODEFORMAT>();

        public SettingsChooser()
        {
            InitializeComponent();

            FillResolutions();
            FillFSAAModes();
        }

        void FillResolutions()
        {
            var deviceInfo = new TVDeviceInfo();

            for (int i = 0; i < deviceInfo.GetDisplayModeCount(); i++)
            {
                TV_MODEFORMAT mode = deviceInfo.GetDisplayMode(i);
                if (mode.Format == 32 && !modes.Any(m => m.Width == mode.Width && m.Height == mode.Height))
                    modes.Add(mode);
            }
            modes.Sort((a, b) => ((b.Width - a.Width) << 16) + b.Height - a.Height);

            foreach (TV_MODEFORMAT mode in modes)
            {
                ResolutionChoice.Items.Add(string.Format("{0} x {1}", mode.Width, mode.Height));

                if(mode.Width == Screen.PrimaryScreen.Bounds.Width &&
                   mode.Height == Screen.PrimaryScreen.Bounds.Height)
                    ResolutionChoice.SelectedIndex = ResolutionChoice.Items.Count - 1;
            }
            if(ResolutionChoice.SelectedIndex == -1)
                ResolutionChoice.SelectedIndex = 0;
        }

        void FillFSAAModes()
        {
            foreach (CONST_TV_MULTISAMPLE_TYPE fsaaMode in Enum.GetValues(typeof(CONST_TV_MULTISAMPLE_TYPE)))
                FsaaChoice.Items.Add(
                    new KeyValuePair<string, CONST_TV_MULTISAMPLE_TYPE>(
                        fsaaMode == 0 ? "None" : ((int)fsaaMode + "x"), fsaaMode
                    ));
            FsaaChoice.SelectedIndex = 0;
        }

        public EngineSettings ChosenSettings
        {
            get
            {
                return new EngineSettings
                {
                    Fullscreen = FullscreenChoice.Checked,
                    FullscreenMode = modes[ResolutionChoice.SelectedIndex],
                    VSync = VSyncCheck.Checked,
                    MultisampleType = ((KeyValuePair<string, CONST_TV_MULTISAMPLE_TYPE>)FsaaChoice.SelectedItem).Value
                };
            }
        }
    }
}
