using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Valg.EVA.Skanning.ServicesModel.Internal
{
    public static class Extensions
    {
        public static string ToUTF8EncodedString(this byte[] bytes)
        {
            return Encoding.UTF8.GetString(bytes);
        }
        
        public static string GetPollingDistrictIdEmlFormat(this string stringToConvert)
        {
            if (String.IsNullOrEmpty(stringToConvert))
                return String.Empty;

            var pollingDistricInEmlFormat = stringToConvert.Substring(0, 2) + ".";
            pollingDistricInEmlFormat += stringToConvert.Substring(2, 2) + ".";
            pollingDistricInEmlFormat += stringToConvert.Substring(4, 4) + ".";
            pollingDistricInEmlFormat += stringToConvert.Substring(8, 6);
            if (stringToConvert.Length > 14)
            {
                pollingDistricInEmlFormat += "." + stringToConvert.Substring(14, 4);
            }
            
            

            return pollingDistricInEmlFormat;
        }

        public static string GetReportingUnitIdEmlFormat(this string stringToConvert)
        {
            if (String.IsNullOrEmpty(stringToConvert))
                return String.Empty;

            var reportingUnitIdInEmlFormat = stringToConvert.Substring(0, 2) + ".";
            reportingUnitIdInEmlFormat += stringToConvert.Substring(2, 2);
            if (stringToConvert.Length > 4)
            {
                reportingUnitIdInEmlFormat += ".";
                reportingUnitIdInEmlFormat += stringToConvert.Substring(4, 4);
            }

            if (stringToConvert.Length > 8)
            {
                reportingUnitIdInEmlFormat += ".";
                reportingUnitIdInEmlFormat += stringToConvert.Substring(8, 6);
            }
            if (stringToConvert.Length > 14)
            {
                reportingUnitIdInEmlFormat += ".";
                reportingUnitIdInEmlFormat += stringToConvert.Substring(14, 4);
            }

            return reportingUnitIdInEmlFormat;
        }

        public static T TypedItem<T>(this IEnumerable<object> untypedItems)
        {
            return (T)untypedItems.First(i => i is T);
        }

        public static T FirstOrDefaultNullSafe<T>(this IEnumerable<T> enumerable)
        {
            if (enumerable == null)
                return default(T);

            return enumerable.FirstOrDefault();
        }

        public static bool IsStringActuallyLongOrInt(this string parseString)
        {
            long result;
            return Int64.TryParse(parseString, out result);
        }
    }
}
