﻿using Microsoft.TeamFoundation.WorkItemTracking.Client;
using System.Linq;

namespace WorkItemMigrationTool.Migration
{
    public class MigrationCategories : BaseMigration
    {
        public MigrationCategories(MigrationOptions options)
            : base(options)
        {
        }

        public override void Start()
        {
            var sourceWorkItems = GetSourceWorkItems();
            var targetWorkItems = GetTargetWorkItems();
            
            for (int i = 0; i < sourceWorkItems.Count; i++)
            {
                var sourceWorkItem = sourceWorkItems[i];
                var targetWorkItem = GetWorkItem(targetWorkItems, sourceWorkItem.Id);
                if (targetWorkItem != null)
                {
                    if (sourceWorkItem.Fields.Contains("Category"))
                    {
                        var sourceCategoryField = sourceWorkItem.Fields["Category"];
                        if (sourceCategoryField.Value != null && sourceCategoryField.Value.ToString() != "")
                        {
                            var tag = $"Category:{sourceCategoryField.Value}";

                            if (string.IsNullOrEmpty(targetWorkItem.Tags))
                            {
                                targetWorkItem.PartialOpen();
                                targetWorkItem.Tags = tag;
                                targetWorkItem.Save();
                            }
                            else if (!targetWorkItem.Tags.Contains(tag))
                            {
                                targetWorkItem.PartialOpen();
                                targetWorkItem.Tags += $"; {tag}";
                                targetWorkItem.Save();
                            }
                        }
                    }
                }

                RaiseProgressChanged(i, sourceWorkItems.Count);
            }
        }

        protected WorkItem GetWorkItem(WorkItemCollection targetCollection, int sourceId)
        {
            return targetCollection.Cast<WorkItem>().FirstOrDefault(x =>
            {
                if (x.Fields.Contains("External ID"))
                {
                    var fieldValue = x.Fields["External ID"].Value;
                    if (fieldValue != null && fieldValue.ToString() != "")
                    {
                        return int.Parse(fieldValue.ToString()) == sourceId;
                    }
                }

                return false;
            });
        }
    }
}
