﻿using System.Collections.Generic;

namespace AsmodeeDigital.Common.Plugin.Utils.Extensions
{
    /// <summary>
    /// Extensions methods for List<>
    /// </summary>
    public static class ListExtension
    {
        /// <summary>
        /// Get the first item of a List
        /// </summary>
        /// <typeparam name="T">Type of the List</typeparam>
        /// <returns>First item of the list</returns>
        public static T First<T>(this List<T> items)
        {
            if (items != null && items.Count > 0)
                return items[0];
            else
                return default(T);
        }

        /// <summary>
        /// Get the last item of a List
        /// If the list is null or contains no item, the default value of the type T is returned
        /// </summary>
        /// <typeparam name="T">Type of the List</typeparam>
        /// <returns>Last item of the list</returns>
        public static T Last<T>(this List<T> items)
        {
            if (items != null && items.Count > 0)
                return items[items.Count - 1];
            else
                return default(T);
        }

        /// <summary>
        /// Get the maximum value af a List<int?>
        /// Returned value can be null if the list is null or contains no item
        /// </summary>
        /// <returns>Maximum value as the list</returns>
        public static int? Max(this List<int?> items)
        {
            int? value = null;

            if (items != null && items.Count > 0)
            {
                for (int i = 0; i < items.Count; i++)
                {
                    if (value == null || items[i] > value)
                        value = items[i];
                }
            }

            return value;
        }

        /// <summary>
        /// Get the maximum value of a List<int>
        /// Returned value can -1 if the list is null or contains no item
        /// </summary>
        /// <returns>Maximum value as the list</returns>
        public static int Max(this List<int> items)
        {
            int value = -1;

            if (items != null && items.Count > 0)
            {
                for (int i = 0; i < items.Count; i++)
                {
                    if (items[i] > value)
                        value = items[i];
                }
            }

            return value;
        }

        /// <summary>
        /// Get the sum of a List<int>
        /// </summary>
        /// <returns>Sum a the list</returns>
        public static int Sum(this List<int> items)
        {
            int value = 0;

            if (items != null && items.Count > 0)
            {
                for (int i = 0; i < items.Count; i++)
                {
                    value += items[i];
                }
            }

            return value;
        }
    }
}
