using Valg.EVA.Skanning.Identity.Area;

namespace Valg.EVA.Skanning.Identity
{
    public class TransferAreaContextIdParser
    {
        private readonly Role role;

        public TransferAreaContextIdParser(Role role)
        {
            this.role = role;
        }

        
        
        
        private bool IsReportingUnitMuncipality
        {
            get
            {
                bool isReportingUnitMuncipality = false;
                var parts = role.ReportingUnitIdentifier.Split('-');
                if (parts.Length == 2)
                {
                    var rightParts = parts[0].Split('.');
                    var leftParts = parts[1].Split('.');
                    if (rightParts.Length == 1 && leftParts.Length == 3)
                    {
                        isReportingUnitMuncipality = true;
                    }
                }
                return isReportingUnitMuncipality;
            }
        }

        
        
        
        private bool IsReportingUnitCounty
        {
            get
            {
                bool isReportingUnitCounty = false;
                var parts = role.ReportingUnitIdentifier.Split('-');
                if (parts.Length == 2)
                {
                    var rightParts = parts[0].Split('.');
                    var leftParts = parts[1].Split('.');
                    if (rightParts.Length == 2 && leftParts.Length == 2)
                    {
                        isReportingUnitCounty = true;
                    }
                }
                return isReportingUnitCounty;
            }
        }

        public static string Parse(Role role)
        {
            return new TransferAreaContextIdParser(role).Parse();
        }

        internal string Parse()
        {
            if (IsReportingUnitMuncipality)
            {
                return MuncipalityLevel();
            }
            else if (IsReportingUnitCounty)
            {
                return CountyLevel();
            }
            else
            {
                return ValueFromToken();
            }
        }

        private string ValueFromToken()
        {
            return role.Area.TokenAreaContextId;
        }

        private string CountyLevel()
        {
            return role.Area.ConvertAreaContextId(AreaDescription.ElectionLevel.County);
        }

        private string MuncipalityLevel()
        {
            return role.Area.ConvertAreaContextId(AreaDescription.ElectionLevel.Municipality);
        }
    }
}
