using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;

namespace TwoCamWPF.Helpers
{

	class CodecInfo
	{
		public string Fcc;
		public string Description;
		public override string ToString()
		{
			return Description + " (" + Fcc + ")";
		}

		public CodecInfo(string fcc, string desc)
		{
			Fcc = fcc.ToUpper();
			Description = desc;
		}

        public static CodecInfo FromFCC(string Fcc)
        {
            CodecInfo result = CodecList.FirstOrDefault(p => p.Fcc == Fcc);
            if (result == null)
                return CodecList.First();
            else
                return result;
        }

        private static CodecInfo[] _CodecList = ReadCodecList();
        public static CodecInfo[] CodecList
        {
            get { return _CodecList; }
            set { _CodecList = value; }
        }

        static CodecInfo[] ReadCodecList()
        {
            string basePath = @"Software\Microsoft\ActiveMovie\devenum\{33D9A760-90C8-11D0-BD43-00A0C911CE86}";

            List<CodecInfo> codecs = new List<CodecInfo>();
            RegistryKey key = null;

            try
            {
                key = Registry.CurrentUser.OpenSubKey(basePath);
                string[] subkeys = key.GetSubKeyNames();

                foreach (string subkey in subkeys)
                {
                    RegistryKey skey = null;
                    try
                    {
                        skey = key.OpenSubKey(subkey);
                        codecs.Add
                        (
                            new CodecInfo
                            (
                                skey.GetValue("FccHandler").ToString(),
                                skey.GetValue("FriendlyName").ToString()
                            )
                        );
                    }
                    catch (Exception)
                    {
                    }
                    if (skey != null)
                        skey.Close();
                }
            }
            catch (Exception)
            {
            }

            if (key != null)
                key.Close();

            return codecs.ToArray();
        }
	}
}
