using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Collections.ObjectModel;

namespace Aitex.UI.RecipeEditor
{
    public class RecipeInfoConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            try
            {
                if (value == null) return "";
                var recipeRows = value as ObservableCollection<RecipeRow>;
                if (recipeRows == null) return "";
                int timeStepRowId = -1;
                for (int i = 0; i < recipeRows.Count; i++)
                {
                    if (recipeRows[i].TechnicalName == "Time")
                    {
                        timeStepRowId = i;
                        break;
                    }
                }
                TimeSpan tspan = new TimeSpan();
                for (int stepNo = 0; stepNo < recipeRows[timeStepRowId].RecipeItems.Count; stepNo++)
                {
                    var timeDuration = recipeRows[timeStepRowId].RecipeItems[stepNo].Value;
                    var timeArr = timeDuration.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                    if (timeArr.Length == 3)
                    {
                        int h, mi, s;
                        if (int.TryParse(timeArr[0], out h) && int.TryParse(timeArr[1], out mi) && int.TryParse(timeArr[2], out s))
                        {
                            var ts = new TimeSpan(h, mi, s);
                            tspan += ts;
                        }
                    }
                }
                return string.Format("共{0}步,总时间{1}:{2}:{3}", recipeRows.Count, (int)tspan.TotalHours, tspan.Minutes, tspan.Seconds);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
            return "";
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return null;
        }
    }
}