using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using TFSWrappers;
using System.Collections.Specialized;
using Microsoft.TeamFoundation.Client;

namespace TFSBuildManager
{
    public partial class EditBuildTypeForm : Form
    {
        public EditBuildTypeForm(TeamFoundationServer tfs, TFSBuildType buildType)
        {
            InitializeComponent();
            tcEditBuildType.TabPages.Remove(tpBuildItems);
            this.tfs = tfs;
            this.buildType = buildType;
            buildType.StartEdit();
            Text = String.Format(Text, buildType.Name);
            SetTextBoxState(txtDescription, buildType.Description);
            SetTextBoxState(txtBuildMachine, buildType.BuildMachine);
            SetTextBoxState(txtBuildDirectory, buildType.BuildDirectoryPath);
            SetTextBoxState(txtDropLocation, buildType.DropLocation);
            SetCheckBoxState(chkRunTests, buildType.RunTest);
            SetComboBoxState(cmbRunCodeAnalysis, buildType.RunCodeAnalysis);
            SetCheckBoxState(chkUpdateAssociatedWorkItems, buildType.UpdateAssociatedWorkItems);
            SetTextBoxState(txtWorkItemTitle, buildType.WorkItemTitle);
            SetTextBoxState(txtWorkItemDescription, buildType.DescriptionText);
            SetTextBoxState(txtBuildLogText, buildType.BuildlogText);
            SetTextBoxState(txtErrorWarningLogText, buildType.ErrorWarningLogText);
            SetTextBoxState(txtWorkItemFieldValues, buildType.WorkItemFieldValues);
            /*foreach (string solutionToBuild in buildType.SolutionsToBuild)
            {
                lvSolutionsToBuild.Items.Add(solutionToBuild);
            }
            foreach (string configuration in buildType.ConfigurationsToBuild)
            {
                string[] splittedConfiguration = configuration.Split('|');
                lvConfigurationToBuild.Items.Add(splittedConfiguration[0]).SubItems.Add(splittedConfiguration[1]);
            }
            txtTestFile.Text = buildType.MetaDataFileInclude.Value;
            string[] testListsToRun = buildType.TestList.Value.Split(';');
            foreach (string testListToRun in testListsToRun)
            {
                lvTestListsToRun.Items.Add(testListToRun);
            }*/
            SetCheckBoxState(chkSkipClean, buildType.AdvancedProperties.SkipClean);
            SetCheckBoxState(chkSkipGet, buildType.AdvancedProperties.SkipGet);
            SetCheckBoxState(chkSkipLabel, buildType.AdvancedProperties.SkipLabel);
            SetCheckBoxState(chkSkipInitializeWorkspace, buildType.AdvancedProperties.SkipInitializeWorkspace);
            SetCheckBoxState(chkSkipPostBuild, buildType.AdvancedProperties.SkipPostBuild);
            SetCheckBoxState(chkSkipDropBuild, buildType.AdvancedProperties.SkipDropBuild);
            SetTextBoxState(txtLabelQueryScope, buildType.AdvancedProperties.LabelQueryScope);
            SetCheckBoxState(chkForceGet, buildType.AdvancedProperties.ForceGet);
            SetCheckBoxState(chkRecursiveGet, buildType.AdvancedProperties.RecursiveGet);
        }

        private TeamFoundationServer tfs;
        private TFSBuildType buildType;

        private bool ConvertValueToBoolean(string value)
        {
            if (value == String.Empty)
            {
                return false;
            }
            else
            {
                return Convert.ToBoolean(value);
            }
        }

        private void DisableControlToolTip(Control control)
        {
            ToolTip toolTip = new ToolTip();
            toolTip.SetToolTip(control, "");
        }

        private void SetControlToolTip(Control control, BuildTypeProperty buildTypeProperty)
        {
            toolTip.ToolTipTitle = buildTypeProperty.Title;
            if (!buildTypeProperty.Exists)
            {
                toolTip.SetToolTip(control, buildTypeProperty.HelpString + Environment.NewLine + "Property is in its default value. Changing the value will create it in the build type file.");
            }
            else
            {
                toolTip.SetToolTip(control, buildTypeProperty.HelpString);
            }
        }

        private void SetCheckBoxState(CheckBox checkBox, BuildTypeProperty buildTypeProperty)
        {
            if (buildTypeProperty.Exists)
            {
                checkBox.Checked = ConvertValueToBoolean(buildTypeProperty.PropertyValue);
            }
            else
            {
                checkBox.Checked = ConvertValueToBoolean(buildTypeProperty.DefaultValue);
            }
            SetControlToolTip(checkBox, buildTypeProperty);
        }

        private void SetTextBoxState(TextBox textBox, BuildTypeProperty buildTypeProperty)
        {
            if (buildTypeProperty.Exists)
            {
                textBox.Text = buildTypeProperty.PropertyValue;
            }
            else
            {
                textBox.Text = buildTypeProperty.DefaultValue;
            }
            SetControlToolTip(textBox, buildTypeProperty);
        }

        private void SetComboBoxState(ComboBox comboBox, BuildTypeProperty buildTypeProperty)
        {
            if (buildTypeProperty.Exists)
            {
                comboBox.SelectedItem = buildTypeProperty.PropertyValue;
            }
            else
            {
                comboBox.SelectedItem = buildTypeProperty.DefaultValue;
            }
            SetControlToolTip(comboBox, buildTypeProperty);
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            try
            {
                buildType.Save();
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        private void txtDescription_TextChanged(object sender, EventArgs e)
        {
            buildType.Description.PropertyValue = txtDescription.Text;
            SetControlToolTip(txtDescription, buildType.Description);
        }

        private void txtBuildMachine_TextChanged(object sender, EventArgs e)
        {
            buildType.BuildMachine.PropertyValue = txtBuildMachine.Text;
            SetControlToolTip(txtBuildMachine, buildType.BuildMachine);
        }

        private void txtBuildDirectory_TextChanged(object sender, EventArgs e)
        {
            buildType.BuildDirectoryPath.PropertyValue = txtBuildDirectory.Text;
            SetControlToolTip(txtBuildDirectory, buildType.BuildDirectoryPath);
        }

        private void txtDropLocation_TextChanged(object sender, EventArgs e)
        {
            buildType.DropLocation.PropertyValue = txtDropLocation.Text;
            SetControlToolTip(txtDropLocation, buildType.DropLocation);
        }

        private void chkRunTests_CheckedChanged(object sender, EventArgs e)
        {
            buildType.RunTest.PropertyValue = Convert.ToString(chkRunTests.Checked);
            SetControlToolTip(chkRunTests, buildType.RunTest);
        }

        private void chkUpdateAssociatedWorkItems_CheckedChanged(object sender, EventArgs e)
        {
            buildType.UpdateAssociatedWorkItems.PropertyValue = Convert.ToString(chkUpdateAssociatedWorkItems.Checked);
            SetControlToolTip(chkUpdateAssociatedWorkItems, buildType.UpdateAssociatedWorkItems);
        }

        private void txtWorkItemTitle_TextChanged(object sender, EventArgs e)
        {
            buildType.WorkItemTitle.PropertyValue = txtWorkItemTitle.Text;
            SetControlToolTip(txtWorkItemTitle, buildType.WorkItemTitle);
        }

        private void txtWorkItemDescription_TextChanged(object sender, EventArgs e)
        {
            buildType.DescriptionText.PropertyValue = txtWorkItemDescription.Text;
            SetControlToolTip(txtWorkItemDescription, buildType.DescriptionText);
        }

        private void txtBuildLogText_TextChanged(object sender, EventArgs e)
        {
            buildType.BuildlogText.PropertyValue = txtBuildLogText.Text;
            SetControlToolTip(txtBuildLogText, buildType.BuildlogText);
        }

        private void txtErrorWarningLogText_TextChanged(object sender, EventArgs e)
        {
            buildType.ErrorWarningLogText.PropertyValue = txtErrorWarningLogText.Text;
            SetControlToolTip(txtErrorWarningLogText, buildType.ErrorWarningLogText);
        }

        private void cmbRunCodeAnalysis_SelectedValueChanged(object sender, EventArgs e)
        {
            buildType.RunCodeAnalysis.PropertyValue = cmbRunCodeAnalysis.Text;
            SetControlToolTip(cmbRunCodeAnalysis, buildType.RunCodeAnalysis);
        }

        private void btnAddSolution_Click(object sender, EventArgs e)
        {
            SelectSourceControlFilesForm frmSelectSourceControlFiles = new SelectSourceControlFilesForm(
                tfs, "Select Solutions To Build", "Select Solutions To Build:",
                "$/" + buildType.ProjectName, new string[] { "*.sln" }, true);
            if (frmSelectSourceControlFiles.ShowDialog() == DialogResult.OK)
            {
                foreach (string file in frmSelectSourceControlFiles.SelectedFiles)
                {
                    buildType.SolutionsToBuild.Add(file);
                    lvSolutionsToBuild.Items.Add(file);
                }
            }
        }

        private void btnEditSolution_Click(object sender, EventArgs e)
        {
            InputQueryForm frmAddItem = new InputQueryForm("Edit Solution", lvSolutionsToBuild.SelectedItems[0].Text);
            if (frmAddItem.ShowDialog() == DialogResult.OK)
            {
                buildType.SolutionsToBuild[buildType.SolutionsToBuild.IndexOf(
                    lvSolutionsToBuild.SelectedItems[0].Text)] = frmAddItem.EnteredValue;
                lvSolutionsToBuild.SelectedItems[0].Text = frmAddItem.EnteredValue;
            }
        }

        private void lvSolutionsToBuild_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnRemoveSolution.Enabled = lvSolutionsToBuild.SelectedItems.Count > 0;
        }

        private void lvConfigurationSoBuild_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnRemoveConfiguration.Enabled = lvConfigurationToBuild.SelectedItems.Count > 0;
            btnEditConfiguration.Enabled = lvConfigurationToBuild.SelectedItems.Count > 0;
        }

        private void btnAddTestList_Click(object sender, EventArgs e)
        {
            SelectTestListsForm frmSelectTestLists = new SelectTestListsForm(tfs,
                txtTestFile.Text.Replace("$(SolutionRoot)", buildType.SolutionRoot).Replace(@"\", "/")/*,
                buildType.TestListsToRun.ToArray()*/);
            if (frmSelectTestLists.ShowDialog() == DialogResult.OK)
            {
                //lvTestListsToRun.Items.Clear();
                foreach (string testList in frmSelectTestLists.SelectedTestLists)
                {
                    lvTestListsToRun.Items.Add(testList);
                }
            }
        }

        private void btnEditTestList_Click(object sender, EventArgs e)
        {
            InputQueryForm frmAddItem = new InputQueryForm("Edit Test List", lvTestListsToRun.SelectedItems[0].Text);
            if (frmAddItem.ShowDialog() == DialogResult.OK)
            {
                string[] testListsToRun = buildType.TestList.PropertyValue.Split(';');
                //Need to take care
                //testListsToRun[lvTestListsToRun.SelectedItems[0].Text] = frmAddItem.EnteredValue;
                lvTestListsToRun.SelectedItems[0].Text = frmAddItem.EnteredValue;
            }
        }

        private void btnRemoveSolution_Click(object sender, EventArgs e)
        {
            buildType.SolutionsToBuild.Remove(lvSolutionsToBuild.SelectedItems[0].Text);
            lvSolutionsToBuild.SelectedItems[0].Remove();
        }

        private void btnRemoveConfiguration_Click(object sender, EventArgs e)
        {
            buildType.ConfigurationsToBuild.Remove(lvConfigurationToBuild.SelectedItems[0].Text + '|' +
                lvConfigurationToBuild.SelectedItems[0].SubItems[1].Text);
            lvConfigurationToBuild.SelectedItems[0].Remove();
        }

        private void btnRemoveTestList_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem listViewItem in lvTestListsToRun.SelectedItems)
            {
                //Need to take care
                //buildType.TestListsToRun.Remove(listViewItem.Text);
                listViewItem.Remove();
            }
        }

        private void btnAddConfiguration_Click(object sender, EventArgs e)
        {
            ConfigurationForm frmConfiguration = new ConfigurationForm("Add Configuration");
            if (frmConfiguration.ShowDialog() == DialogResult.OK)
            {
                buildType.ConfigurationsToBuild.Add(frmConfiguration.Flavor + '|' + frmConfiguration.Platfrom);
                lvConfigurationToBuild.Items.Add(frmConfiguration.Flavor).SubItems.Add(frmConfiguration.Platfrom);
            }
        }

        private void btnEditConfiguration_Click(object sender, EventArgs e)
        {
            ConfigurationForm frmConfiguration = new ConfigurationForm("Edit Configuration", lvConfigurationToBuild.SelectedItems[0].Text,
                lvConfigurationToBuild.SelectedItems[0].SubItems[1].Text);
            if (frmConfiguration.ShowDialog() == DialogResult.OK)
            {
                buildType.ConfigurationsToBuild[buildType.ConfigurationsToBuild.IndexOf(
                    lvConfigurationToBuild.SelectedItems[0].Text + '|' +
                    lvConfigurationToBuild.SelectedItems[0].SubItems[1].Text)] =
                    frmConfiguration.Flavor + '|' + frmConfiguration.Platfrom;
                lvConfigurationToBuild.SelectedItems[0].Text = frmConfiguration.Flavor;
                lvConfigurationToBuild.SelectedItems[0].SubItems[1].Text = frmConfiguration.Platfrom;
            }
        }

        private void btnBrowseTestFile_Click(object sender, EventArgs e)
        {
            SelectSourceControlFilesForm frmSelectSourceControlFiles = new SelectSourceControlFilesForm(
                tfs, "Select Test File", "Select Test File:",
                "$/" + buildType.ProjectName, new string[] { "*.vsmdi" }, false);
            if (frmSelectSourceControlFiles.ShowDialog() == DialogResult.OK)
            {
                buildType.MetaDataFileInclude.Value = frmSelectSourceControlFiles.SelectedFiles[0];
                txtTestFile.Text = frmSelectSourceControlFiles.SelectedFiles[0];
            }
        }

        private void txtTestFile_TextChanged(object sender, EventArgs e)
        {
            btnAddTestList.Enabled = ((txtTestFile.Text != null) && (txtTestFile.Text != String.Empty));
            if ((txtTestFile.Text == null) || (txtTestFile.Text == String.Empty))
            {
                lvTestListsToRun.Items.Clear();
            }
        }

        private void lvTestListsToRun_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnRemoveTestList.Enabled = lvTestListsToRun.SelectedItems.Count > 0;
        }

        private void txtWorkItemFieldValues_TextChanged(object sender, EventArgs e)
        {
            buildType.WorkItemFieldValues.PropertyValue = txtWorkItemFieldValues.Text;
            SetTextBoxState(txtWorkItemFieldValues, buildType.WorkItemFieldValues);
        }

        private void UpdateCheckBoxAdvancedProperty(CheckBox checkBox, BuildTypeProperty buildTypeProperty)
        {
            if (checkBox.Checked)
            {
                buildTypeProperty.PropertyValue = checkBox.Checked.ToString();
            }
            else
            {
                buildTypeProperty.Remove();
            }
            SetControlToolTip(checkBox, buildTypeProperty);
        }

        private void chkSkipClean_CheckedChanged(object sender, EventArgs e)
        {
            UpdateCheckBoxAdvancedProperty(chkSkipClean, buildType.AdvancedProperties.SkipClean);
        }

        private void chkSkipGet_CheckedChanged(object sender, EventArgs e)
        {
            UpdateCheckBoxAdvancedProperty(chkSkipGet, buildType.AdvancedProperties.SkipGet);
        }

        private void chkSkipLabel_CheckedChanged(object sender, EventArgs e)
        {
            UpdateCheckBoxAdvancedProperty(chkSkipLabel, buildType.AdvancedProperties.SkipLabel);
        }

        private void chkSkipInitializeWorkspace_CheckedChanged(object sender, EventArgs e)
        {
            UpdateCheckBoxAdvancedProperty(chkSkipInitializeWorkspace, buildType.AdvancedProperties.SkipInitializeWorkspace);
        }

        private void chkSkipPostBuild_CheckedChanged(object sender, EventArgs e)
        {
            UpdateCheckBoxAdvancedProperty(chkSkipPostBuild, buildType.AdvancedProperties.SkipPostBuild);
        }

        private void chkSkipDropBuild_CheckedChanged(object sender, EventArgs e)
        {
            UpdateCheckBoxAdvancedProperty(chkSkipDropBuild, buildType.AdvancedProperties.SkipDropBuild);
        }

        private void chkSkipWorkItemCreation_CheckedChanged(object sender, EventArgs e)
        {
            UpdateCheckBoxAdvancedProperty(chkSkipWorkItemCreation, buildType.AdvancedProperties.SkipWorkItemCreation);
        }

        private void txtLabelQueryScope_TextChanged(object sender, EventArgs e)
        {
            if ((txtLabelQueryScope.Text != null) && (txtLabelQueryScope.Text != String.Empty) &&
                (txtLabelQueryScope.Text != buildType.AdvancedProperties.LabelQueryScope.DefaultValue))
            {
                buildType.AdvancedProperties.LabelQueryScope.PropertyValue = txtLabelQueryScope.Text;
            }
            else
            {
                buildType.AdvancedProperties.LabelQueryScope.Remove();
            }
            SetControlToolTip(txtLabelQueryScope, buildType.AdvancedProperties.LabelQueryScope);
        }

        private void chkForceGet_CheckedChanged(object sender, EventArgs e)
        {
            UpdateCheckBoxAdvancedProperty(chkForceGet, buildType.AdvancedProperties.ForceGet);
        }

        private void chkRecursiveGet_CheckedChanged(object sender, EventArgs e)
        {
            UpdateCheckBoxAdvancedProperty(chkRecursiveGet, buildType.AdvancedProperties.RecursiveGet);
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            buildType.CancelEdit();           
        }
    }
}