// Copyright (C) 2013 João Pedro Correia - All Rights Reserved
// Code under the terms of the GPLv2 license
// URL: http://flowstudio.codeplex.com

namespace FlowStudio.ViewModel.Data
{
    using System.Activities;
    using System.Activities.Presentation.Model;
    using System.Linq;

    public class OutlineActivityItem : OutlinePropertyItem
    {
        private readonly string displayText;

        private readonly string propertyName;

        public OutlineActivityItem(ModelItem activityModelItem)
            : base(activityModelItem)
        {
            // Get display text and Id
            var activity = activityModelItem.GetCurrentValue() as Activity;

            if (activity != null)
            {
                displayText = !string.IsNullOrEmpty(activity.DisplayName)
                                  ? activity.DisplayName
                                  : activityModelItem.ItemType.Name;

                Id = activity.Id;
            }

            displayText = displayText ?? activityModelItem.Name;

            // Get property name
            propertyName = activityModelItem.Source != null ? activityModelItem.Source.Name : string.Empty;

            // Traverse the rest of the properties looking for child activities and variables

            foreach (var property in activityModelItem.Properties.Where(p => p.Value != null))
            {
                if (property.PropertyType.IsSubclassOf(typeof (Activity)) ||
                    property.PropertyType.IsAssignableFrom(typeof (Activity)))
                {
                    InnerItems.Add(new OutlineActivityItem(property.Value));
                }
                else if (property.IsCollection &&
                         property.Collection != null &&
                         property.PropertyType.IsGenericType)
                {
                    var genericTypes = property.PropertyType.GetGenericArguments();

                    if (genericTypes.Length == 1 && genericTypes[0].IsAssignableFrom(typeof (Activity)))
                    {
                        InnerItems.Add(new OutlineActivitiesHolderItem(property.Value));
                    }
                    else if (genericTypes.Length == 1 && genericTypes[0].IsAssignableFrom(typeof (Variable)))
                    {
                        InnerItems.Add(new OutlineVariablesHolderItem(property.Value));
                    }
                }
            }
        }

        public override string DisplayText
        {
            get { return displayText; }
        }

        public override string PropertyName
        {
            get { return propertyName; }
        }

        public string Id { get; private set; }
    }
}
