using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using Microsoft.TeamFoundation.Client;
using System.Net;
using System.Web.Configuration;
using System.Collections.Specialized;
using Microsoft.TeamFoundation.Proxy;
using System.Windows.Forms;
using Microsoft.Win32;

namespace TFSWrappers
{
    public enum ConfigurationType
    {
        WindowsApplication,
        WebApplication
    }

    public static class TFSFunctions
    {
        public const string FrameworkRootRegistryKey = @"SOFTWARE\Microsoft\.NETFramework";
        public const string InstallRootRegistryValue = "InstallRoot";
        public const string FrameworkVersion = "v2.0.50727";

        public static string GetMSBuildBinPath()
        {
            try
            {
                RegistryKey rootKey = Registry.LocalMachine;
                return rootKey.OpenSubKey(FrameworkRootRegistryKey).GetValue(InstallRootRegistryValue).ToString() + @"\" + FrameworkVersion;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static NameValueCollection GetTFSAppSettingsSection(ConfigurationType configurationType)
        {
            NameValueCollection appSettings = new NameValueCollection();
            if (configurationType == ConfigurationType.WindowsApplication)
            {
                appSettings = (NameValueCollection)ConfigurationManager.GetSection(TFSConstants.TFSAppSettingsConfigSectionName);
            }
            else if (configurationType == ConfigurationType.WebApplication)
            {
                appSettings = (NameValueCollection)WebConfigurationManager.GetWebApplicationSection(TFSConstants.TFSAppSettingsConfigSectionName);
            }
            return appSettings;
        }

        public static TeamFoundationServer GetServer(string serverName)
        {
            TeamFoundationServer teamServer = new TeamFoundationServer(serverName, CredentialCache.DefaultCredentials);
            teamServer.EnsureAuthenticated();
            return teamServer;
        }

        public static TeamFoundationServer GetServerDialog()
        {
            DomainProjectPicker domainProjectPicker = new DomainProjectPicker(DomainProjectPickerMode.AllowProjectSelect);
            if (domainProjectPicker.ShowDialog() == DialogResult.OK)
            {
                TeamFoundationServer tfs = new TeamFoundationServer(domainProjectPicker.SelectedServer.Name, new UICredentialsProvider());
                tfs.Authenticate();
                return tfs;
            }
            else
            {
                return null;
            }
        }
    }
}
