
using System;
using System.Collections.Generic;
using Au.Gov.Sbr.Xbrl.Document;
using Au.Gov.Sbr.Xbrl.Metadata;
using System.Linq;
using System.Xml;
using System.Text.RegularExpressions;
using DataContracts;

namespace Ato.EN.IntegrationServices.CodeGenerationCGLS
{
    public class CGLS2017Consumer
    {

        private static Regex StripWhitespace = new Regex(@"\s*");

        #region Helper/Validation Methods
        private static bool? ToBoolean(string str)
        {
            bool returnValue;
            string value = (str ?? "").Trim();
            if (value == "0" || value == "1")
                return Convert.ToBoolean(Convert.ToInt32(value));
            
            if (Boolean.TryParse(value, out returnValue))
                return returnValue;
            return null;
        }

        private static string GetValueOrEmpty(bool? val)
        {
            return (val.HasValue) ? val.ToString() : string.Empty;
        }

        private static string GetValueOrEmpty(DateTime? val)
        {
            return (val.HasValue) ? val.ToString() : string.Empty;
        }

        /// <summary>
        /// Derives the SBR element location.
        /// </summary>
        /// <param name="sbrElement">The SBR element.</param>
        /// <param name="addOccurrenceIndex">if set to <c>true</c> [add occurrence the occurrence index to the path].</param>
        /// <returns></returns>
        private static string DeriveSbrElementLocation(SBRElement sbrElement, bool addOccurrenceIndex = false)
        {
            if (sbrElement == null) return "/xbrli:xbrl";
            int xpathOccurrence = sbrElement.OccurrenceIndex + 1;
            string location;

            if (addOccurrenceIndex)
            {
                location = "/" + sbrElement.NamespacePrefix + ":" + sbrElement.Name + "[" +
                           xpathOccurrence + "]";
            }
            else
            {
                location = "/" + sbrElement.NamespacePrefix + ":" + sbrElement.Name;
            }

            if (sbrElement.IsInTuple)
            {
                location = DeriveSbrElementLocation(sbrElement.ParentTuple, true) + location;
            }
            else
            {
                location = "/xbrli:xbrl" + location;
            }

            return location;
        }

        private static bool IsMatch(int? field, string expression, RegexOptions options = RegexOptions.None)
        {
            if (field == null)
                return false;
            else
                return Regex.IsMatch(Convert.ToString(field.Value), expression, options);
        }

        private static bool IsMatch(string field, string expression, RegexOptions options = RegexOptions.None)
        {
            if (field == null)
                return false;
            else
                return Regex.IsMatch(field, expression, options);
        }

        public DateTime AsDate(string dateAsString)
        {
            DateTime response = DateTime.MinValue;
            DateTime date;

            if (DateTime.TryParse(dateAsString, out date))
            {
                response = date;
            }

            return response;
        }

         #endregion

        public CGLS2017 Consume(SBRDocument sbrDocument)
        {
            List<ProcessMessageDocument> errors;
            return Consume(sbrDocument, false, out errors);
        }

        /// <summary>
        /// Allows for validation of rules that can not be generated and must run at a lower level.
        /// A sub-class will need to be created with an override for this method - which does nothing in its base implementation.
        /// </summary>
        /// <param name="sbrDocument">The SBR document.</param>
        /// <param name="populatedReportElementsMap">The populated report elements map can be used to find data elements and tuples.</param>
        /// <param name="contextArray">The context array can be used to find context values.</param>
        /// <param name="errors">The errors collection is to be populated with validation results.</param>
        protected virtual void ValidateUnsupportedRules(SBRDocument sbrDocument, IDictionary<string, SBRElement> populatedReportElementsMap, SBRContext[] contextArray, List<ProcessMessageDocument> errors)
        {

        }

        public CGLS2017 Consume(SBRDocument sbrDocument, bool validationMode, out List<ProcessMessageDocument> errors)
        {
            CGLS2017 report;
            report = new CGLS2017();
            errors = new List<ProcessMessageDocument>();

            SBRContext[] contextArray;
            IDictionary<string, SBRElement> populatedReportElementsMap;

            contextArray = sbrDocument.ContextsMap.Values.ToArray();
            populatedReportElementsMap = sbrDocument.PopulatedChildElementsMap ?? new Dictionary<string, SBRElement>();

            if (validationMode) ValidateUnsupportedRules(sbrDocument, populatedReportElementsMap, contextArray, errors);

            /// <summary>
            /// Current element being extracted
            /// </summary>
            SBRElement currentValue = null;
            /// <summary>
            /// Current elements being extracted
            /// </summary>
            IList<SBRElement> currentValues = null;
            /// <summary>
            /// Current occurrances being extracted
            /// </summary>
            IList<SBRElement> currentOccurrences = null;
            /// <summary>
            /// Working Variable for date time variables
            /// </summary>
            DateTime currentDateTimeValue;
            /// <summary>
            /// Working Variable for boolean variables
            /// </summary>
            bool currentBooleanValue;
            /// <summary>
            /// Working Variable for decimal variables
            /// </summary>
            decimal currentDecimalValue;
            /// <summary>
            /// Working Variable for integer variables
            /// </summary>
            int currentIntValue;
            /// <summary>
            /// Working Variable for long variables
            /// </summary>
            long currentLongValue;
            XmlDocumentFragment currentSegment;
            XmlNamespaceManager currentNamespaceManager;
            XmlNode currentNode;
    
            #region sbrRPContext
            IEnumerable<SBRContext> sbrRPContexts = null;
            SBRContext sbrRPContext = null;
    
            sbrRPContexts = contextArray.Where(
                c => c.Period != null && c.Period.PeriodType == SBRPeriod_PeriodType.DURATION &&
                c.Segment != null && c.Segment.ExplicitOrTypedDimensionDomains.Count == 1 && 
                (c.Segment.ExplicitOrTypedDimensionDomains.Any(dd => dd.DimensionType == SBRExplicitOrTypedDimensionDomain_Type.EXPLICIT && dd.Dimension.EndsWith("}ReportPartyTypeDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}ReportingParty")) ));
            Dictionary<string, IList<SBRElement>> sbrPopulatedRPElementsMap = new Dictionary<string, IList<SBRElement>>();
            if (sbrRPContexts != null && sbrRPContexts.Count() > 0)
            {
                sbrRPContext = sbrRPContexts.First();
        
                report.RPId = sbrRPContext.Id;
                report.RPIdentifier = sbrRPContext.EntityIdentifier;
                report.RPIdentifierScheme = sbrRPContext.EntityScheme;
        
                report.RPCount = sbrRPContexts.Count();
                report.RPExists = true;
                report.RPOccurrenceIndex = Array.IndexOf(contextArray, sbrRPContext) + 1;
                report.RPLastOccurrenceIndex = Array.IndexOf(contextArray, sbrRPContexts.Last()) + 1;
        

                if (report.RPIdentifierScheme == "http://www.ato.gov.au/tfn") report.RPIdentifierTFN = report.RPIdentifier;
    
                report.RPStartDate = ((SBRDurationPeriod)sbrRPContext.Period).DurationStartAsDateObject;
                report.RPEndDate = ((SBRDurationPeriod)sbrRPContext.Period).DurationEndAsDateObject;
        
                sbrPopulatedRPElementsMap = new System.Collections.Generic.Dictionary<string, IList<SBRElement>>();
                for (int i = 0; i < sbrRPContexts.Count(); i++)
                {
                    sbrRPContext = sbrRPContexts.ElementAt(i);
            
                    IList<SBRElement> elements = sbrDocument.ElementsByContextId[sbrRPContext.Id];
                    if (elements != null)
                    {
                        for (int e = 0; e < elements.Count(); e++)
                        {
                            SBRElement currentElement = elements[e];
                            if (currentElement == null || currentElement.IsInTuple) continue; // Don't add tuple elements here, they will be found through a different map.
                            if (sbrPopulatedRPElementsMap.ContainsKey("{" + currentElement.Namespace + "}" + currentElement.Name))
                            {
                                sbrPopulatedRPElementsMap["{" + currentElement.Namespace + "}" + currentElement.Name].Add(currentElement);
                            }
                            else
                            {
                                sbrPopulatedRPElementsMap.Add("{" + currentElement.Namespace + "}" + currentElement.Name, new List<SBRElement> { currentElement } );
                            }
                        }
                    }
                    report.CGLS1 = report.RPIdentifier;
            
                    if (sbrPopulatedRPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Identifiers.AustralianBusinessNumber.Identifier", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS3 = currentValues[0].Value;
                    }
        
                    IEnumerable<SBRElement> sbrOrganisationNameDetailsCollection;
                    if (populatedReportElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}OrganisationNameDetails", out currentValue))
                        sbrOrganisationNameDetailsCollection = currentValue.Occurrences;
                    else
                        sbrOrganisationNameDetailsCollection = null;
            
                    #region sbrOrganisationNameDetailsCollection
            
                    if (sbrOrganisationNameDetailsCollection != null)
                    {
                        report.OrganisationNameDetailsCollectionExists = true;
                        report.OrganisationNameDetailsCollectionCount = sbrOrganisationNameDetailsCollection.Count();
                
                        IEnumerable<SBRElement> sbrOrganisationNameDetailsCollection_MN_RPCollection;
                        sbrOrganisationNameDetailsCollection_MN_RPCollection = sbrOrganisationNameDetailsCollection.Where(
                            ce => ce.ChildElements != null && 
                            ce.ChildElements.Any(te => te.Name == "OrganisationNameDetails.OrganisationalNameType.Code" && te.Value == "MN" &&
                            sbrRPContexts.Contains(te.Context)));
                        if (sbrOrganisationNameDetailsCollection_MN_RPCollection != null && sbrOrganisationNameDetailsCollection_MN_RPCollection.Count() > 0)
                        {
                            SBRElement sbrOrganisationNameDetailsCollection_MN_RP;
                            sbrOrganisationNameDetailsCollection_MN_RP = sbrOrganisationNameDetailsCollection_MN_RPCollection.ElementAt(0);
                
                            IDictionary<string, SBRElement> sbrOrganisationNameDetailsCollection_MN_RPTupleElementMap;
                            sbrOrganisationNameDetailsCollection_MN_RPTupleElementMap = sbrOrganisationNameDetailsCollection_MN_RP.PopulatedChildElementsMap ?? new Dictionary<string, SBRElement>();
                
                            report.OrganisationNameDetailsCollection_MN_RPExists = true;
                            report.OrganisationNameDetailsCollection_MN_RPCount = sbrOrganisationNameDetailsCollection_MN_RPCollection.Count();
                            report.OrganisationNameDetailsCollection_MN_RPOccurrenceIndex = sbrOrganisationNameDetailsCollection_MN_RP.OccurrenceIndex + 1;
                            report.OrganisationNameDetailsCollection_MN_RPLastOccurrenceIndex = sbrOrganisationNameDetailsCollection_MN_RPCollection.Last().OccurrenceIndex + 1;
                    
                            if (sbrOrganisationNameDetailsCollection_MN_RPTupleElementMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}OrganisationNameDetails.OrganisationalNameType.Code", out currentValue))
                            {
                                if (!currentValue.IsNil) report.CGLS100 = currentValue.Value;
                            }
                    
                            if (sbrOrganisationNameDetailsCollection_MN_RPTupleElementMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}OrganisationNameDetails.OrganisationalName.Text", out currentValue))
                            {
                                if (!currentValue.IsNil) report.CGLS2 = currentValue.Value;
                            }
                        }  
                    } 
                    #endregion End of Tuple sbrOrganisationNameDetailsCollection
                    if (validationMode) ValidateRPOrganisationNameDetailsCollection(errors, sbrOrganisationNameDetailsCollection, sbrRPContexts, report);
            
            
                    if (sbrPopulatedRPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.TransferredLossUtilisedApportionmentRulesApplied.Indicator", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS35 = ToBoolean(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.TransferredLossCancelledByHeadCompany.Indicator", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS36 = ToBoolean(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.CarriedForward.BusinessContinuityTestPassed.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS117 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Capital.Losses.CarriedForward.BusinessContinuityTestPassedNet.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS118 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.DeductedOwnershipTestFailContinuityTestPass.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS115 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Capital.Losses.DeductedOwnershipTestFailContinuityTestPass.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS116 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.CarriedForward.ComplyingSuperannuationClass.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS119 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Capital.Losses.CarriedForward.ComplyingSuperannuationClassNet.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS120 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.ControlledForeignCompany.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS82 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.ControlledForeignCompanyDeducted.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS69 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.CarriedForward.ControlledForeignCompany.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS70 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.BalanceOfTaxLossesBroughtForwardFromPriorYear.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS83 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.Uplift.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS104 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.TransferredFromJoiningEntitiesUnderSubdivision707A.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS85 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.TransferredWithNilAvailableFractionApplied.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS94 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.ForgivenDebtNet.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS86 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.Incurred.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS87 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.ConversionOfExcessFrankingOffsets.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS88 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.ExemptIncomeNet.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS89 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.Forgone.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS90 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.Total.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS91 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.TransferredOut.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS92 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.CarriedForward.LaterIncomeYearsTotal.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS93 = decimal.Parse(currentValues[0].Value);
                    }
                } 
            } 
            #endregion End of Context sbrRPContext
    
            #region sbrTRFRContext
            IEnumerable<SBRContext> sbrTRFRContexts = null;
            SBRContext sbrTRFRContext = null;
    
            sbrTRFRContexts = contextArray.Where(
                c => c.Period != null && c.Period.PeriodType == SBRPeriod_PeriodType.DURATION &&
                c.Segment != null && c.Segment.ExplicitOrTypedDimensionDomains.Count == 1 && 
                (c.Segment.ExplicitOrTypedDimensionDomains.Any(dd => dd.DimensionType == SBRExplicitOrTypedDimensionDomain_Type.EXPLICIT && dd.Dimension.EndsWith("}ReportPartyTypeDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}Transferor")) ));
            Dictionary<string, IList<SBRElement>> sbrPopulatedTRFRElementsMap = new Dictionary<string, IList<SBRElement>>();
            if (sbrTRFRContexts != null && sbrTRFRContexts.Count() > 0)
            {
        
                report.TRFRContextCollection = new List<CGLS2017.TRFRContext>();
                for (int i = 0; i < sbrTRFRContexts.Count(); i++)
                {
                    sbrTRFRContext = sbrTRFRContexts.ElementAt(i);
                    CGLS2017.TRFRContext trfrContext = new CGLS2017.TRFRContext();
                    report.TRFRContextCollection.Add(trfrContext);
            
                    trfrContext.Id = sbrTRFRContext.Id;
                    trfrContext.Identifier = sbrTRFRContext.EntityIdentifier;
                    trfrContext.IdentifierScheme = sbrTRFRContext.EntityScheme;
            
                    trfrContext.Count = sbrTRFRContexts.Count();
                    trfrContext.Exists = true;
                    trfrContext.OccurrenceIndex = Array.IndexOf(contextArray, sbrTRFRContext) + 1;
                    trfrContext.LastOccurrenceIndex = Array.IndexOf(contextArray, sbrTRFRContexts.Last()) + 1;
            
    
                    if (trfrContext.IdentifierScheme == "http://www.ato.gov.au/tfn") trfrContext.IdentifierTFN = trfrContext.Identifier;
        
                    trfrContext.StartDate = ((SBRDurationPeriod)sbrTRFRContext.Period).DurationStartAsDateObject;
                    trfrContext.EndDate = ((SBRDurationPeriod)sbrTRFRContext.Period).DurationEndAsDateObject;
            
                    sbrPopulatedTRFRElementsMap = new System.Collections.Generic.Dictionary<string, IList<SBRElement>>();
            
                    IList<SBRElement> elements = sbrDocument.ElementsByContextId[sbrTRFRContext.Id];
                    if (elements != null)
                    {
                        for (int e = 0; e < elements.Count(); e++)
                        {
                            SBRElement currentElement = elements[e];
                            if (currentElement == null) continue; // Don't add tuple elements here, they will be found through a different map.
                            if (sbrPopulatedTRFRElementsMap.ContainsKey("{" + currentElement.Namespace + "}" + currentElement.Name))
                            {
                                sbrPopulatedTRFRElementsMap["{" + currentElement.Namespace + "}" + currentElement.Name].Add(currentElement);
                            }
                            else
                            {
                                sbrPopulatedTRFRElementsMap.Add("{" + currentElement.Namespace + "}" + currentElement.Name, new List<SBRElement> { currentElement } );
                            }
                        }
                    }
                    trfrContext.CGLS14 = trfrContext.Identifier;
            
                    if (sbrPopulatedTRFRElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.TransferredDeducted.Fraction", out currentValues))
                    {
                        if (!currentValues[0].IsNil) trfrContext.CGLS108 = (currentValues[0].Numerator / currentValues[0].Denominator);
                        if (!currentValues[0].IsNil) trfrContext.CGLS108Numerator = currentValues[0].Numerator;
                        if (!currentValues[0].IsNil) trfrContext.CGLS108Denominator = currentValues[0].Denominator;
                    }
            
                    if (sbrPopulatedTRFRElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.TransferredDeducted.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) trfrContext.CGLS109 = decimal.Parse(currentValues[0].Value);
                    }
                    trfrContext.CGLS29 = trfrContext.Identifier;
            
                    if (sbrPopulatedTRFRElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Capital.Losses.TransferredApplied.Fraction", out currentValues))
                    {
                        if (!currentValues[0].IsNil) trfrContext.CGLS113 = (currentValues[0].Numerator / currentValues[0].Denominator);
                        if (!currentValues[0].IsNil) trfrContext.CGLS113Numerator = currentValues[0].Numerator;
                        if (!currentValues[0].IsNil) trfrContext.CGLS113Denominator = currentValues[0].Denominator;
                    }
            
                    if (sbrPopulatedTRFRElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Capital.Losses.TransferredApplied.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) trfrContext.CGLS114 = decimal.Parse(currentValues[0].Value);
                    }
        } 
            } 
            #endregion End of Context sbrTRFRContext
    
            #region sbrJEContext
            IEnumerable<SBRContext> sbrJEContexts = null;
            SBRContext sbrJEContext = null;
    
            sbrJEContexts = contextArray.Where(
                c => c.Period != null && c.Period.PeriodType == SBRPeriod_PeriodType.DURATION &&
                c.Segment != null && c.Segment.ExplicitOrTypedDimensionDomains.Count == 1 && 
                (c.Segment.ExplicitOrTypedDimensionDomains.Any(dd => dd.DimensionType == SBRExplicitOrTypedDimensionDomain_Type.EXPLICIT && dd.Dimension.EndsWith("}ReportPartyTypeDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}JoiningEntity")) ));
            Dictionary<string, IList<SBRElement>> sbrPopulatedJEElementsMap = new Dictionary<string, IList<SBRElement>>();
            if (sbrJEContexts != null && sbrJEContexts.Count() > 0)
            {
        
                report.JEContextCollection = new List<CGLS2017.JEContext>();
                for (int i = 0; i < sbrJEContexts.Count(); i++)
                {
                    sbrJEContext = sbrJEContexts.ElementAt(i);
                    CGLS2017.JEContext jeContext = new CGLS2017.JEContext();
                    report.JEContextCollection.Add(jeContext);
            
                    jeContext.Id = sbrJEContext.Id;
                    jeContext.Identifier = sbrJEContext.EntityIdentifier;
                    jeContext.IdentifierScheme = sbrJEContext.EntityScheme;
            
                    jeContext.Count = sbrJEContexts.Count();
                    jeContext.Exists = true;
                    jeContext.OccurrenceIndex = Array.IndexOf(contextArray, sbrJEContext) + 1;
                    jeContext.LastOccurrenceIndex = Array.IndexOf(contextArray, sbrJEContexts.Last()) + 1;
            
    
                    if (jeContext.IdentifierScheme == "http://www.ato.gov.au/tfn") jeContext.IdentifierTFN = jeContext.Identifier;
        
                    jeContext.StartDate = ((SBRDurationPeriod)sbrJEContext.Period).DurationStartAsDateObject;
                    jeContext.EndDate = ((SBRDurationPeriod)sbrJEContext.Period).DurationEndAsDateObject;
            
                    sbrPopulatedJEElementsMap = new System.Collections.Generic.Dictionary<string, IList<SBRElement>>();
            
                    IList<SBRElement> elements = sbrDocument.ElementsByContextId[sbrJEContext.Id];
                    if (elements != null)
                    {
                        for (int e = 0; e < elements.Count(); e++)
                        {
                            SBRElement currentElement = elements[e];
                            if (currentElement == null) continue; // Don't add tuple elements here, they will be found through a different map.
                            if (sbrPopulatedJEElementsMap.ContainsKey("{" + currentElement.Namespace + "}" + currentElement.Name))
                            {
                                sbrPopulatedJEElementsMap["{" + currentElement.Namespace + "}" + currentElement.Name].Add(currentElement);
                            }
                            else
                            {
                                sbrPopulatedJEElementsMap.Add("{" + currentElement.Namespace + "}" + currentElement.Name, new List<SBRElement> { currentElement } );
                            }
                        }
                    }
                    jeContext.CGLS37 = jeContext.Identifier;
            
                    if (sbrPopulatedJEElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.TransferredLossCancelledByHeadCompany.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) jeContext.CGLS38 = decimal.Parse(currentValues[0].Value);
                    }
        } 
            } 
            #endregion End of Context sbrJEContext
    
            #region sbrRPCOTPContext
            IEnumerable<SBRContext> sbrRPCOTPContexts = null;
            SBRContext sbrRPCOTPContext = null;
    
            sbrRPCOTPContexts = contextArray.Where(
                c => c.Period != null && c.Period.PeriodType == SBRPeriod_PeriodType.DURATION &&
                c.Segment != null && c.Segment.ExplicitOrTypedDimensionDomains.Count == 2 && 
                (c.Segment.ExplicitOrTypedDimensionDomains.Any(dd => dd.DimensionType == SBRExplicitOrTypedDimensionDomain_Type.EXPLICIT && dd.Dimension.EndsWith("}ReportPartyTypeDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}ReportingParty"))  && 
                (c.Segment.ExplicitOrTypedDimensionDomains.Any(dd => dd.DimensionType == SBRExplicitOrTypedDimensionDomain_Type.EXPLICIT && dd.Dimension.EndsWith("}MajorityOwnershipAndControlTestsTypeDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}COTPassed")) )));
            Dictionary<string, IList<SBRElement>> sbrPopulatedRPCOTPElementsMap = new Dictionary<string, IList<SBRElement>>();
            if (sbrRPCOTPContexts != null && sbrRPCOTPContexts.Count() > 0)
            {
                sbrRPCOTPContext = sbrRPCOTPContexts.First();
        
                report.RPCOTPId = sbrRPCOTPContext.Id;
                report.RPCOTPIdentifier = sbrRPCOTPContext.EntityIdentifier;
                report.RPCOTPIdentifierScheme = sbrRPCOTPContext.EntityScheme;
        
                report.RPCOTPCount = sbrRPCOTPContexts.Count();
                report.RPCOTPExists = true;
                report.RPCOTPOccurrenceIndex = Array.IndexOf(contextArray, sbrRPCOTPContext) + 1;
                report.RPCOTPLastOccurrenceIndex = Array.IndexOf(contextArray, sbrRPCOTPContexts.Last()) + 1;
        

                if (report.RPCOTPIdentifierScheme == "http://www.ato.gov.au/tfn") report.RPCOTPIdentifierTFN = report.RPCOTPIdentifier;
    
                report.RPCOTPStartDate = ((SBRDurationPeriod)sbrRPCOTPContext.Period).DurationStartAsDateObject;
                report.RPCOTPEndDate = ((SBRDurationPeriod)sbrRPCOTPContext.Period).DurationEndAsDateObject;
        
                sbrPopulatedRPCOTPElementsMap = new System.Collections.Generic.Dictionary<string, IList<SBRElement>>();
                for (int i = 0; i < sbrRPCOTPContexts.Count(); i++)
                {
                    sbrRPCOTPContext = sbrRPCOTPContexts.ElementAt(i);
            
                    IList<SBRElement> elements = sbrDocument.ElementsByContextId[sbrRPCOTPContext.Id];
                    if (elements != null)
                    {
                        for (int e = 0; e < elements.Count(); e++)
                        {
                            SBRElement currentElement = elements[e];
                            if (currentElement == null || currentElement.IsInTuple) continue; // Don't add tuple elements here, they will be found through a different map.
                            if (sbrPopulatedRPCOTPElementsMap.ContainsKey("{" + currentElement.Namespace + "}" + currentElement.Name))
                            {
                                sbrPopulatedRPCOTPElementsMap["{" + currentElement.Namespace + "}" + currentElement.Name].Add(currentElement);
                            }
                            else
                            {
                                sbrPopulatedRPCOTPElementsMap.Add("{" + currentElement.Namespace + "}" + currentElement.Name, new List<SBRElement> { currentElement } );
                            }
                        }
                    }
            
                    if (sbrPopulatedRPCOTPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.TransferredFromJoiningEntitiesIncludingHeadCompany.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS5 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPCOTPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.TransferredFromJoiningEntitiesAfterConsolidation.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS8 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPCOTPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Capital.Losses.TransferredFromJoiningEntitiesIncludingHeadCompanyNet.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS20 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPCOTPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Capital.Losses.TransferredFromJoiningEntitiesAfterConsolidation.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS23 = decimal.Parse(currentValues[0].Value);
                    }
                } 
            } 
            #endregion End of Context sbrRPCOTPContext
    
            #region sbrRPCOTFContext
            IEnumerable<SBRContext> sbrRPCOTFContexts = null;
            SBRContext sbrRPCOTFContext = null;
    
            sbrRPCOTFContexts = contextArray.Where(
                c => c.Period != null && c.Period.PeriodType == SBRPeriod_PeriodType.DURATION &&
                c.Segment != null && c.Segment.ExplicitOrTypedDimensionDomains.Count == 2 && 
                (c.Segment.ExplicitOrTypedDimensionDomains.Any(dd => dd.DimensionType == SBRExplicitOrTypedDimensionDomain_Type.EXPLICIT && dd.Dimension.EndsWith("}ReportPartyTypeDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}ReportingParty"))  && 
                (c.Segment.ExplicitOrTypedDimensionDomains.Any(dd => dd.DimensionType == SBRExplicitOrTypedDimensionDomain_Type.EXPLICIT && dd.Dimension.EndsWith("}MajorityOwnershipAndControlTestsTypeDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}COTFailedBCTPassed")) )));
            Dictionary<string, IList<SBRElement>> sbrPopulatedRPCOTFElementsMap = new Dictionary<string, IList<SBRElement>>();
            if (sbrRPCOTFContexts != null && sbrRPCOTFContexts.Count() > 0)
            {
                sbrRPCOTFContext = sbrRPCOTFContexts.First();
        
                report.RPCOTFId = sbrRPCOTFContext.Id;
                report.RPCOTFIdentifier = sbrRPCOTFContext.EntityIdentifier;
                report.RPCOTFIdentifierScheme = sbrRPCOTFContext.EntityScheme;
        
                report.RPCOTFCount = sbrRPCOTFContexts.Count();
                report.RPCOTFExists = true;
                report.RPCOTFOccurrenceIndex = Array.IndexOf(contextArray, sbrRPCOTFContext) + 1;
                report.RPCOTFLastOccurrenceIndex = Array.IndexOf(contextArray, sbrRPCOTFContexts.Last()) + 1;
        

                if (report.RPCOTFIdentifierScheme == "http://www.ato.gov.au/tfn") report.RPCOTFIdentifierTFN = report.RPCOTFIdentifier;
    
                report.RPCOTFStartDate = ((SBRDurationPeriod)sbrRPCOTFContext.Period).DurationStartAsDateObject;
                report.RPCOTFEndDate = ((SBRDurationPeriod)sbrRPCOTFContext.Period).DurationEndAsDateObject;
        
                sbrPopulatedRPCOTFElementsMap = new System.Collections.Generic.Dictionary<string, IList<SBRElement>>();
                for (int i = 0; i < sbrRPCOTFContexts.Count(); i++)
                {
                    sbrRPCOTFContext = sbrRPCOTFContexts.ElementAt(i);
            
                    IList<SBRElement> elements = sbrDocument.ElementsByContextId[sbrRPCOTFContext.Id];
                    if (elements != null)
                    {
                        for (int e = 0; e < elements.Count(); e++)
                        {
                            SBRElement currentElement = elements[e];
                            if (currentElement == null || currentElement.IsInTuple) continue; // Don't add tuple elements here, they will be found through a different map.
                            if (sbrPopulatedRPCOTFElementsMap.ContainsKey("{" + currentElement.Namespace + "}" + currentElement.Name))
                            {
                                sbrPopulatedRPCOTFElementsMap["{" + currentElement.Namespace + "}" + currentElement.Name].Add(currentElement);
                            }
                            else
                            {
                                sbrPopulatedRPCOTFElementsMap.Add("{" + currentElement.Namespace + "}" + currentElement.Name, new List<SBRElement> { currentElement } );
                            }
                        }
                    }
            
                    if (sbrPopulatedRPCOTFElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.TransferredFromJoiningEntitiesIncludingHeadCompany.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS6 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPCOTFElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.TransferredFromJoiningEntitiesAfterConsolidation.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS9 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPCOTFElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Capital.Losses.TransferredFromJoiningEntitiesIncludingHeadCompanyNet.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS21 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPCOTFElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Capital.Losses.TransferredFromJoiningEntitiesAfterConsolidation.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS24 = decimal.Parse(currentValues[0].Value);
                    }
                } 
            } 
            #endregion End of Context sbrRPCOTFContext
    
            #region sbrRPCOTTContext
            IEnumerable<SBRContext> sbrRPCOTTContexts = null;
            SBRContext sbrRPCOTTContext = null;
    
            sbrRPCOTTContexts = contextArray.Where(
                c => c.Period != null && c.Period.PeriodType == SBRPeriod_PeriodType.DURATION &&
                c.Segment != null && c.Segment.ExplicitOrTypedDimensionDomains.Count == 2 && 
                (c.Segment.ExplicitOrTypedDimensionDomains.Any(dd => dd.DimensionType == SBRExplicitOrTypedDimensionDomain_Type.EXPLICIT && dd.Dimension.EndsWith("}ReportPartyTypeDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}ReportingParty"))  && 
                (c.Segment.ExplicitOrTypedDimensionDomains.Any(dd => dd.DimensionType == SBRExplicitOrTypedDimensionDomain_Type.EXPLICIT && dd.Dimension.EndsWith("}MajorityOwnershipAndControlTestsTypeDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}COTTrust")) )));
            Dictionary<string, IList<SBRElement>> sbrPopulatedRPCOTTElementsMap = new Dictionary<string, IList<SBRElement>>();
            if (sbrRPCOTTContexts != null && sbrRPCOTTContexts.Count() > 0)
            {
                sbrRPCOTTContext = sbrRPCOTTContexts.First();
        
                report.RPCOTTId = sbrRPCOTTContext.Id;
                report.RPCOTTIdentifier = sbrRPCOTTContext.EntityIdentifier;
                report.RPCOTTIdentifierScheme = sbrRPCOTTContext.EntityScheme;
        
                report.RPCOTTCount = sbrRPCOTTContexts.Count();
                report.RPCOTTExists = true;
                report.RPCOTTOccurrenceIndex = Array.IndexOf(contextArray, sbrRPCOTTContext) + 1;
                report.RPCOTTLastOccurrenceIndex = Array.IndexOf(contextArray, sbrRPCOTTContexts.Last()) + 1;
        

                if (report.RPCOTTIdentifierScheme == "http://www.ato.gov.au/tfn") report.RPCOTTIdentifierTFN = report.RPCOTTIdentifier;
    
                report.RPCOTTStartDate = ((SBRDurationPeriod)sbrRPCOTTContext.Period).DurationStartAsDateObject;
                report.RPCOTTEndDate = ((SBRDurationPeriod)sbrRPCOTTContext.Period).DurationEndAsDateObject;
        
                sbrPopulatedRPCOTTElementsMap = new System.Collections.Generic.Dictionary<string, IList<SBRElement>>();
                for (int i = 0; i < sbrRPCOTTContexts.Count(); i++)
                {
                    sbrRPCOTTContext = sbrRPCOTTContexts.ElementAt(i);
            
                    IList<SBRElement> elements = sbrDocument.ElementsByContextId[sbrRPCOTTContext.Id];
                    if (elements != null)
                    {
                        for (int e = 0; e < elements.Count(); e++)
                        {
                            SBRElement currentElement = elements[e];
                            if (currentElement == null || currentElement.IsInTuple) continue; // Don't add tuple elements here, they will be found through a different map.
                            if (sbrPopulatedRPCOTTElementsMap.ContainsKey("{" + currentElement.Namespace + "}" + currentElement.Name))
                            {
                                sbrPopulatedRPCOTTElementsMap["{" + currentElement.Namespace + "}" + currentElement.Name].Add(currentElement);
                            }
                            else
                            {
                                sbrPopulatedRPCOTTElementsMap.Add("{" + currentElement.Namespace + "}" + currentElement.Name, new List<SBRElement> { currentElement } );
                            }
                        }
                    }
            
                    if (sbrPopulatedRPCOTTElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.TransferredFromJoiningEntitiesIncludingHeadCompany.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS7 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPCOTTElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.TransferredFromJoiningEntitiesAfterConsolidation.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS10 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPCOTTElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Capital.Losses.TransferredFromJoiningEntitiesIncludingHeadCompanyNet.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS22 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPCOTTElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Capital.Losses.TransferredFromJoiningEntitiesAfterConsolidation.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS25 = decimal.Parse(currentValues[0].Value);
                    }
                } 
            } 
            #endregion End of Context sbrRPCOTTContext
    
            #region sbrRPGRPContext
            IEnumerable<SBRContext> sbrRPGRPContexts = null;
            SBRContext sbrRPGRPContext = null;
    
            sbrRPGRPContexts = contextArray.Where(
                c => c.Period != null && c.Period.PeriodType == SBRPeriod_PeriodType.DURATION &&
                c.Segment != null && c.Segment.ExplicitOrTypedDimensionDomains.Count == 2 && 
                (c.Segment.ExplicitOrTypedDimensionDomains.Any(dd => dd.DimensionType == SBRExplicitOrTypedDimensionDomain_Type.EXPLICIT && dd.Dimension.EndsWith("}ReportPartyTypeDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}ReportingParty"))  && 
                (c.Segment.ExplicitOrTypedDimensionDomains.Any(dd => dd.DimensionType == SBRExplicitOrTypedDimensionDomain_Type.EXPLICIT && dd.Dimension.EndsWith("}LossGenerationSourceDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}Group")) )));
            Dictionary<string, IList<SBRElement>> sbrPopulatedRPGRPElementsMap = new Dictionary<string, IList<SBRElement>>();
            if (sbrRPGRPContexts != null && sbrRPGRPContexts.Count() > 0)
            {
                sbrRPGRPContext = sbrRPGRPContexts.First();
        
                report.RPGRPId = sbrRPGRPContext.Id;
                report.RPGRPIdentifier = sbrRPGRPContext.EntityIdentifier;
                report.RPGRPIdentifierScheme = sbrRPGRPContext.EntityScheme;
        
                report.RPGRPCount = sbrRPGRPContexts.Count();
                report.RPGRPExists = true;
                report.RPGRPOccurrenceIndex = Array.IndexOf(contextArray, sbrRPGRPContext) + 1;
                report.RPGRPLastOccurrenceIndex = Array.IndexOf(contextArray, sbrRPGRPContexts.Last()) + 1;
        

                if (report.RPGRPIdentifierScheme == "http://www.ato.gov.au/tfn") report.RPGRPIdentifierTFN = report.RPGRPIdentifier;
    
                report.RPGRPStartDate = ((SBRDurationPeriod)sbrRPGRPContext.Period).DurationStartAsDateObject;
                report.RPGRPEndDate = ((SBRDurationPeriod)sbrRPGRPContext.Period).DurationEndAsDateObject;
        
                sbrPopulatedRPGRPElementsMap = new System.Collections.Generic.Dictionary<string, IList<SBRElement>>();
                for (int i = 0; i < sbrRPGRPContexts.Count(); i++)
                {
                    sbrRPGRPContext = sbrRPGRPContexts.ElementAt(i);
            
                    IList<SBRElement> elements = sbrDocument.ElementsByContextId[sbrRPGRPContext.Id];
                    if (elements != null)
                    {
                        for (int e = 0; e < elements.Count(); e++)
                        {
                            SBRElement currentElement = elements[e];
                            if (currentElement == null || currentElement.IsInTuple) continue; // Don't add tuple elements here, they will be found through a different map.
                            if (sbrPopulatedRPGRPElementsMap.ContainsKey("{" + currentElement.Namespace + "}" + currentElement.Name))
                            {
                                sbrPopulatedRPGRPElementsMap["{" + currentElement.Namespace + "}" + currentElement.Name].Add(currentElement);
                            }
                            else
                            {
                                sbrPopulatedRPGRPElementsMap.Add("{" + currentElement.Namespace + "}" + currentElement.Name, new List<SBRElement> { currentElement } );
                            }
                        }
                    }
            
                    if (sbrPopulatedRPGRPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.Deducted.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS105 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPGRPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.CarriedForward.Total.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS17 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPGRPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Capital.Losses.AppliedNet.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS110 = decimal.Parse(currentValues[0].Value);
                    }
                } 
            } 
            #endregion End of Context sbrRPGRPContext
    
            #region sbrRPTRFDContext
            IEnumerable<SBRContext> sbrRPTRFDContexts = null;
            SBRContext sbrRPTRFDContext = null;
    
            sbrRPTRFDContexts = contextArray.Where(
                c => c.Period != null && c.Period.PeriodType == SBRPeriod_PeriodType.DURATION &&
                c.Segment != null && c.Segment.ExplicitOrTypedDimensionDomains.Count == 2 && 
                (c.Segment.ExplicitOrTypedDimensionDomains.Any(dd => dd.DimensionType == SBRExplicitOrTypedDimensionDomain_Type.EXPLICIT && dd.Dimension.EndsWith("}ReportPartyTypeDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}ReportingParty"))  && 
                (c.Segment.ExplicitOrTypedDimensionDomains.Any(dd => dd.DimensionType == SBRExplicitOrTypedDimensionDomain_Type.EXPLICIT && dd.Dimension.EndsWith("}LossGenerationSourceDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}Transferred")) )));
            Dictionary<string, IList<SBRElement>> sbrPopulatedRPTRFDElementsMap = new Dictionary<string, IList<SBRElement>>();
            if (sbrRPTRFDContexts != null && sbrRPTRFDContexts.Count() > 0)
            {
                sbrRPTRFDContext = sbrRPTRFDContexts.First();
        
                report.RPTRFDId = sbrRPTRFDContext.Id;
                report.RPTRFDIdentifier = sbrRPTRFDContext.EntityIdentifier;
                report.RPTRFDIdentifierScheme = sbrRPTRFDContext.EntityScheme;
        
                report.RPTRFDCount = sbrRPTRFDContexts.Count();
                report.RPTRFDExists = true;
                report.RPTRFDOccurrenceIndex = Array.IndexOf(contextArray, sbrRPTRFDContext) + 1;
                report.RPTRFDLastOccurrenceIndex = Array.IndexOf(contextArray, sbrRPTRFDContexts.Last()) + 1;
        

                if (report.RPTRFDIdentifierScheme == "http://www.ato.gov.au/tfn") report.RPTRFDIdentifierTFN = report.RPTRFDIdentifier;
    
                report.RPTRFDStartDate = ((SBRDurationPeriod)sbrRPTRFDContext.Period).DurationStartAsDateObject;
                report.RPTRFDEndDate = ((SBRDurationPeriod)sbrRPTRFDContext.Period).DurationEndAsDateObject;
        
                sbrPopulatedRPTRFDElementsMap = new System.Collections.Generic.Dictionary<string, IList<SBRElement>>();
                for (int i = 0; i < sbrRPTRFDContexts.Count(); i++)
                {
                    sbrRPTRFDContext = sbrRPTRFDContexts.ElementAt(i);
            
                    IList<SBRElement> elements = sbrDocument.ElementsByContextId[sbrRPTRFDContext.Id];
                    if (elements != null)
                    {
                        for (int e = 0; e < elements.Count(); e++)
                        {
                            SBRElement currentElement = elements[e];
                            if (currentElement == null || currentElement.IsInTuple) continue; // Don't add tuple elements here, they will be found through a different map.
                            if (sbrPopulatedRPTRFDElementsMap.ContainsKey("{" + currentElement.Namespace + "}" + currentElement.Name))
                            {
                                sbrPopulatedRPTRFDElementsMap["{" + currentElement.Namespace + "}" + currentElement.Name].Add(currentElement);
                            }
                            else
                            {
                                sbrPopulatedRPTRFDElementsMap.Add("{" + currentElement.Namespace + "}" + currentElement.Name, new List<SBRElement> { currentElement } );
                            }
                        }
                    }
            
                    if (sbrPopulatedRPTRFDElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.Deducted.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS106 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPTRFDElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.CarriedForward.Total.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS18 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPTRFDElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Capital.Losses.AppliedNet.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS111 = decimal.Parse(currentValues[0].Value);
                    }
                } 
            } 
            #endregion End of Context sbrRPTRFDContext
    
            #region sbrRPTOTContext
            IEnumerable<SBRContext> sbrRPTOTContexts = null;
            SBRContext sbrRPTOTContext = null;
    
            sbrRPTOTContexts = contextArray.Where(
                c => c.Period != null && c.Period.PeriodType == SBRPeriod_PeriodType.DURATION &&
                c.Segment != null && c.Segment.ExplicitOrTypedDimensionDomains.Count == 2 && 
                (c.Segment.ExplicitOrTypedDimensionDomains.Any(dd => dd.DimensionType == SBRExplicitOrTypedDimensionDomain_Type.EXPLICIT && dd.Dimension.EndsWith("}ReportPartyTypeDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}ReportingParty"))  && 
                (c.Segment.ExplicitOrTypedDimensionDomains.Any(dd => dd.DimensionType == SBRExplicitOrTypedDimensionDomain_Type.EXPLICIT && dd.Dimension.EndsWith("}LossGenerationSourceDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}Total")) )));
            Dictionary<string, IList<SBRElement>> sbrPopulatedRPTOTElementsMap = new Dictionary<string, IList<SBRElement>>();
            if (sbrRPTOTContexts != null && sbrRPTOTContexts.Count() > 0)
            {
                sbrRPTOTContext = sbrRPTOTContexts.First();
        
                report.RPTOTId = sbrRPTOTContext.Id;
                report.RPTOTIdentifier = sbrRPTOTContext.EntityIdentifier;
                report.RPTOTIdentifierScheme = sbrRPTOTContext.EntityScheme;
        
                report.RPTOTCount = sbrRPTOTContexts.Count();
                report.RPTOTExists = true;
                report.RPTOTOccurrenceIndex = Array.IndexOf(contextArray, sbrRPTOTContext) + 1;
                report.RPTOTLastOccurrenceIndex = Array.IndexOf(contextArray, sbrRPTOTContexts.Last()) + 1;
        

                if (report.RPTOTIdentifierScheme == "http://www.ato.gov.au/tfn") report.RPTOTIdentifierTFN = report.RPTOTIdentifier;
    
                report.RPTOTStartDate = ((SBRDurationPeriod)sbrRPTOTContext.Period).DurationStartAsDateObject;
                report.RPTOTEndDate = ((SBRDurationPeriod)sbrRPTOTContext.Period).DurationEndAsDateObject;
        
                sbrPopulatedRPTOTElementsMap = new System.Collections.Generic.Dictionary<string, IList<SBRElement>>();
                for (int i = 0; i < sbrRPTOTContexts.Count(); i++)
                {
                    sbrRPTOTContext = sbrRPTOTContexts.ElementAt(i);
            
                    IList<SBRElement> elements = sbrDocument.ElementsByContextId[sbrRPTOTContext.Id];
                    if (elements != null)
                    {
                        for (int e = 0; e < elements.Count(); e++)
                        {
                            SBRElement currentElement = elements[e];
                            if (currentElement == null || currentElement.IsInTuple) continue; // Don't add tuple elements here, they will be found through a different map.
                            if (sbrPopulatedRPTOTElementsMap.ContainsKey("{" + currentElement.Namespace + "}" + currentElement.Name))
                            {
                                sbrPopulatedRPTOTElementsMap["{" + currentElement.Namespace + "}" + currentElement.Name].Add(currentElement);
                            }
                            else
                            {
                                sbrPopulatedRPTOTElementsMap.Add("{" + currentElement.Namespace + "}" + currentElement.Name, new List<SBRElement> { currentElement } );
                            }
                        }
                    }
            
                    if (sbrPopulatedRPTOTElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.Deducted.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS107 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPTOTElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.CarriedForward.Total.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS19 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPTOTElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Capital.Losses.AppliedNet.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS112 = decimal.Parse(currentValues[0].Value);
                    }
                } 
            } 
            #endregion End of Context sbrRPTOTContext
    
            #region sbrRPGRPInstantContext
            IEnumerable<SBRContext> sbrRPGRPInstantContexts = null;
            SBRContext sbrRPGRPInstantContext = null;
    
            sbrRPGRPInstantContexts = contextArray.Where(
                c => c.Period != null && c.Period.PeriodType == SBRPeriod_PeriodType.INSTANT &&
                c.Segment != null && c.Segment.ExplicitOrTypedDimensionDomains.Count == 2 && 
                (c.Segment.ExplicitOrTypedDimensionDomains.Any(dd => dd.DimensionType == SBRExplicitOrTypedDimensionDomain_Type.EXPLICIT && dd.Dimension.EndsWith("}ReportPartyTypeDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}ReportingParty"))  && 
                (c.Segment.ExplicitOrTypedDimensionDomains.Any(dd => dd.DimensionType == SBRExplicitOrTypedDimensionDomain_Type.EXPLICIT && dd.Dimension.EndsWith("}LossGenerationSourceDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}Group")) )));
            Dictionary<string, IList<SBRElement>> sbrPopulatedRPGRPInstantElementsMap = new Dictionary<string, IList<SBRElement>>();
            if (sbrRPGRPInstantContexts != null && sbrRPGRPInstantContexts.Count() > 0)
            {
                sbrRPGRPInstantContext = sbrRPGRPInstantContexts.First();
        
                report.RPGRPInstantId = sbrRPGRPInstantContext.Id;
                report.RPGRPInstantIdentifier = sbrRPGRPInstantContext.EntityIdentifier;
                report.RPGRPInstantIdentifierScheme = sbrRPGRPInstantContext.EntityScheme;
        
                report.RPGRPInstantCount = sbrRPGRPInstantContexts.Count();
                report.RPGRPInstantExists = true;
                report.RPGRPInstantOccurrenceIndex = Array.IndexOf(contextArray, sbrRPGRPInstantContext) + 1;
                report.RPGRPInstantLastOccurrenceIndex = Array.IndexOf(contextArray, sbrRPGRPInstantContexts.Last()) + 1;
        

                if (report.RPGRPInstantIdentifierScheme == "http://www.ato.gov.au/tfn") report.RPGRPInstantIdentifierTFN = report.RPGRPInstantIdentifier;
    
                report.RPGRPInstantInstantDate = ((SBRInstantPeriod)sbrRPGRPInstantContext.Period).InstantAsDateObject;
        
                sbrPopulatedRPGRPInstantElementsMap = new System.Collections.Generic.Dictionary<string, IList<SBRElement>>();
                for (int i = 0; i < sbrRPGRPInstantContexts.Count(); i++)
                {
                    sbrRPGRPInstantContext = sbrRPGRPInstantContexts.ElementAt(i);
            
                    IList<SBRElement> elements = sbrDocument.ElementsByContextId[sbrRPGRPInstantContext.Id];
                    if (elements != null)
                    {
                        for (int e = 0; e < elements.Count(); e++)
                        {
                            SBRElement currentElement = elements[e];
                            if (currentElement == null || currentElement.IsInTuple) continue; // Don't add tuple elements here, they will be found through a different map.
                            if (sbrPopulatedRPGRPInstantElementsMap.ContainsKey("{" + currentElement.Namespace + "}" + currentElement.Name))
                            {
                                sbrPopulatedRPGRPInstantElementsMap["{" + currentElement.Namespace + "}" + currentElement.Name].Add(currentElement);
                            }
                            else
                            {
                                sbrPopulatedRPGRPInstantElementsMap.Add("{" + currentElement.Namespace + "}" + currentElement.Name, new List<SBRElement> { currentElement } );
                            }
                        }
                    }
            
                    if (sbrPopulatedRPGRPInstantElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Capital.Losses.CarriedForward.Net.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS32 = decimal.Parse(currentValues[0].Value);
                    }
                } 
            } 
            #endregion End of Context sbrRPGRPInstantContext
    
            #region sbrRPTRFDInstantContext
            IEnumerable<SBRContext> sbrRPTRFDInstantContexts = null;
            SBRContext sbrRPTRFDInstantContext = null;
    
            sbrRPTRFDInstantContexts = contextArray.Where(
                c => c.Period != null && c.Period.PeriodType == SBRPeriod_PeriodType.INSTANT &&
                c.Segment != null && c.Segment.ExplicitOrTypedDimensionDomains.Count == 2 && 
                (c.Segment.ExplicitOrTypedDimensionDomains.Any(dd => dd.DimensionType == SBRExplicitOrTypedDimensionDomain_Type.EXPLICIT && dd.Dimension.EndsWith("}ReportPartyTypeDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}ReportingParty"))  && 
                (c.Segment.ExplicitOrTypedDimensionDomains.Any(dd => dd.DimensionType == SBRExplicitOrTypedDimensionDomain_Type.EXPLICIT && dd.Dimension.EndsWith("}LossGenerationSourceDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}Transferred")) )));
            Dictionary<string, IList<SBRElement>> sbrPopulatedRPTRFDInstantElementsMap = new Dictionary<string, IList<SBRElement>>();
            if (sbrRPTRFDInstantContexts != null && sbrRPTRFDInstantContexts.Count() > 0)
            {
                sbrRPTRFDInstantContext = sbrRPTRFDInstantContexts.First();
        
                report.RPTRFDInstantId = sbrRPTRFDInstantContext.Id;
                report.RPTRFDInstantIdentifier = sbrRPTRFDInstantContext.EntityIdentifier;
                report.RPTRFDInstantIdentifierScheme = sbrRPTRFDInstantContext.EntityScheme;
        
                report.RPTRFDInstantCount = sbrRPTRFDInstantContexts.Count();
                report.RPTRFDInstantExists = true;
                report.RPTRFDInstantOccurrenceIndex = Array.IndexOf(contextArray, sbrRPTRFDInstantContext) + 1;
                report.RPTRFDInstantLastOccurrenceIndex = Array.IndexOf(contextArray, sbrRPTRFDInstantContexts.Last()) + 1;
        

                if (report.RPTRFDInstantIdentifierScheme == "http://www.ato.gov.au/tfn") report.RPTRFDInstantIdentifierTFN = report.RPTRFDInstantIdentifier;
    
                report.RPTRFDInstantInstantDate = ((SBRInstantPeriod)sbrRPTRFDInstantContext.Period).InstantAsDateObject;
        
                sbrPopulatedRPTRFDInstantElementsMap = new System.Collections.Generic.Dictionary<string, IList<SBRElement>>();
                for (int i = 0; i < sbrRPTRFDInstantContexts.Count(); i++)
                {
                    sbrRPTRFDInstantContext = sbrRPTRFDInstantContexts.ElementAt(i);
            
                    IList<SBRElement> elements = sbrDocument.ElementsByContextId[sbrRPTRFDInstantContext.Id];
                    if (elements != null)
                    {
                        for (int e = 0; e < elements.Count(); e++)
                        {
                            SBRElement currentElement = elements[e];
                            if (currentElement == null || currentElement.IsInTuple) continue; // Don't add tuple elements here, they will be found through a different map.
                            if (sbrPopulatedRPTRFDInstantElementsMap.ContainsKey("{" + currentElement.Namespace + "}" + currentElement.Name))
                            {
                                sbrPopulatedRPTRFDInstantElementsMap["{" + currentElement.Namespace + "}" + currentElement.Name].Add(currentElement);
                            }
                            else
                            {
                                sbrPopulatedRPTRFDInstantElementsMap.Add("{" + currentElement.Namespace + "}" + currentElement.Name, new List<SBRElement> { currentElement } );
                            }
                        }
                    }
            
                    if (sbrPopulatedRPTRFDInstantElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Capital.Losses.CarriedForward.Net.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS33 = decimal.Parse(currentValues[0].Value);
                    }
                } 
            } 
            #endregion End of Context sbrRPTRFDInstantContext
    
            #region sbrRPTOTInstantContext
            IEnumerable<SBRContext> sbrRPTOTInstantContexts = null;
            SBRContext sbrRPTOTInstantContext = null;
    
            sbrRPTOTInstantContexts = contextArray.Where(
                c => c.Period != null && c.Period.PeriodType == SBRPeriod_PeriodType.INSTANT &&
                c.Segment != null && c.Segment.ExplicitOrTypedDimensionDomains.Count == 2 && 
                (c.Segment.ExplicitOrTypedDimensionDomains.Any(dd => dd.DimensionType == SBRExplicitOrTypedDimensionDomain_Type.EXPLICIT && dd.Dimension.EndsWith("}ReportPartyTypeDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}ReportingParty"))  && 
                (c.Segment.ExplicitOrTypedDimensionDomains.Any(dd => dd.DimensionType == SBRExplicitOrTypedDimensionDomain_Type.EXPLICIT && dd.Dimension.EndsWith("}LossGenerationSourceDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}Total")) )));
            Dictionary<string, IList<SBRElement>> sbrPopulatedRPTOTInstantElementsMap = new Dictionary<string, IList<SBRElement>>();
            if (sbrRPTOTInstantContexts != null && sbrRPTOTInstantContexts.Count() > 0)
            {
                sbrRPTOTInstantContext = sbrRPTOTInstantContexts.First();
        
                report.RPTOTInstantId = sbrRPTOTInstantContext.Id;
                report.RPTOTInstantIdentifier = sbrRPTOTInstantContext.EntityIdentifier;
                report.RPTOTInstantIdentifierScheme = sbrRPTOTInstantContext.EntityScheme;
        
                report.RPTOTInstantCount = sbrRPTOTInstantContexts.Count();
                report.RPTOTInstantExists = true;
                report.RPTOTInstantOccurrenceIndex = Array.IndexOf(contextArray, sbrRPTOTInstantContext) + 1;
                report.RPTOTInstantLastOccurrenceIndex = Array.IndexOf(contextArray, sbrRPTOTInstantContexts.Last()) + 1;
        

                if (report.RPTOTInstantIdentifierScheme == "http://www.ato.gov.au/tfn") report.RPTOTInstantIdentifierTFN = report.RPTOTInstantIdentifier;
    
                report.RPTOTInstantInstantDate = ((SBRInstantPeriod)sbrRPTOTInstantContext.Period).InstantAsDateObject;
        
                sbrPopulatedRPTOTInstantElementsMap = new System.Collections.Generic.Dictionary<string, IList<SBRElement>>();
                for (int i = 0; i < sbrRPTOTInstantContexts.Count(); i++)
                {
                    sbrRPTOTInstantContext = sbrRPTOTInstantContexts.ElementAt(i);
            
                    IList<SBRElement> elements = sbrDocument.ElementsByContextId[sbrRPTOTInstantContext.Id];
                    if (elements != null)
                    {
                        for (int e = 0; e < elements.Count(); e++)
                        {
                            SBRElement currentElement = elements[e];
                            if (currentElement == null || currentElement.IsInTuple) continue; // Don't add tuple elements here, they will be found through a different map.
                            if (sbrPopulatedRPTOTInstantElementsMap.ContainsKey("{" + currentElement.Namespace + "}" + currentElement.Name))
                            {
                                sbrPopulatedRPTOTInstantElementsMap["{" + currentElement.Namespace + "}" + currentElement.Name].Add(currentElement);
                            }
                            else
                            {
                                sbrPopulatedRPTOTInstantElementsMap.Add("{" + currentElement.Namespace + "}" + currentElement.Name, new List<SBRElement> { currentElement } );
                            }
                        }
                    }
            
                    if (sbrPopulatedRPTOTInstantElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Capital.Losses.CarriedForward.Net.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS34 = decimal.Parse(currentValues[0].Value);
                    }
                } 
            } 
            #endregion End of Context sbrRPTOTInstantContext
    
            #region sbrRPY0Context
            IEnumerable<SBRContext> sbrRPY0Contexts = null;
            SBRContext sbrRPY0Context = null;
    
            sbrRPY0Contexts = contextArray.Where(
                c => c.Period != null && c.Period.PeriodType == SBRPeriod_PeriodType.DURATION &&
                c.Segment != null && c.Segment.ExplicitOrTypedDimensionDomains.Count == 2 && 
                (c.Segment.ExplicitOrTypedDimensionDomains.Any(dd => dd.DimensionType == SBRExplicitOrTypedDimensionDomain_Type.EXPLICIT && dd.Dimension.EndsWith("}ReportPartyTypeDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}ReportingParty"))  && 
                (c.Segment.ExplicitOrTypedDimensionDomains.Any(dd => dd.DimensionType == SBRExplicitOrTypedDimensionDomain_Type.EXPLICIT && dd.Dimension.EndsWith("}RelativePeriodDurationDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}Y0")) )));
            Dictionary<string, IList<SBRElement>> sbrPopulatedRPY0ElementsMap = new Dictionary<string, IList<SBRElement>>();
            if (sbrRPY0Contexts != null && sbrRPY0Contexts.Count() > 0)
            {
                sbrRPY0Context = sbrRPY0Contexts.First();
        
                report.RPY0Id = sbrRPY0Context.Id;
                report.RPY0Identifier = sbrRPY0Context.EntityIdentifier;
                report.RPY0IdentifierScheme = sbrRPY0Context.EntityScheme;
        
                report.RPY0Count = sbrRPY0Contexts.Count();
                report.RPY0Exists = true;
                report.RPY0OccurrenceIndex = Array.IndexOf(contextArray, sbrRPY0Context) + 1;
                report.RPY0LastOccurrenceIndex = Array.IndexOf(contextArray, sbrRPY0Contexts.Last()) + 1;
        

                if (report.RPY0IdentifierScheme == "http://www.ato.gov.au/tfn") report.RPY0IdentifierTFN = report.RPY0Identifier;
    
                report.RPY0StartDate = ((SBRDurationPeriod)sbrRPY0Context.Period).DurationStartAsDateObject;
                report.RPY0EndDate = ((SBRDurationPeriod)sbrRPY0Context.Period).DurationEndAsDateObject;
        
                sbrPopulatedRPY0ElementsMap = new System.Collections.Generic.Dictionary<string, IList<SBRElement>>();
                for (int i = 0; i < sbrRPY0Contexts.Count(); i++)
                {
                    sbrRPY0Context = sbrRPY0Contexts.ElementAt(i);
            
                    IList<SBRElement> elements = sbrDocument.ElementsByContextId[sbrRPY0Context.Id];
                    if (elements != null)
                    {
                        for (int e = 0; e < elements.Count(); e++)
                        {
                            SBRElement currentElement = elements[e];
                            if (currentElement == null || currentElement.IsInTuple) continue; // Don't add tuple elements here, they will be found through a different map.
                            if (sbrPopulatedRPY0ElementsMap.ContainsKey("{" + currentElement.Namespace + "}" + currentElement.Name))
                            {
                                sbrPopulatedRPY0ElementsMap["{" + currentElement.Namespace + "}" + currentElement.Name].Add(currentElement);
                            }
                            else
                            {
                                sbrPopulatedRPY0ElementsMap.Add("{" + currentElement.Namespace + "}" + currentElement.Name, new List<SBRElement> { currentElement } );
                            }
                        }
                    }
            
                    if (sbrPopulatedRPY0ElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.TransferredContinuityTestFail.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS39 = decimal.Parse(currentValues[0].Value);
                    }
                } 
            } 
            #endregion End of Context sbrRPY0Context
    
            #region sbrRPY0Minus1Context
            IEnumerable<SBRContext> sbrRPY0Minus1Contexts = null;
            SBRContext sbrRPY0Minus1Context = null;
    
            sbrRPY0Minus1Contexts = contextArray.Where(
                c => c.Period != null && c.Period.PeriodType == SBRPeriod_PeriodType.DURATION &&
                c.Segment != null && c.Segment.ExplicitOrTypedDimensionDomains.Count == 2 && 
                (c.Segment.ExplicitOrTypedDimensionDomains.Any(dd => dd.DimensionType == SBRExplicitOrTypedDimensionDomain_Type.EXPLICIT && dd.Dimension.EndsWith("}ReportPartyTypeDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}ReportingParty"))  && 
                (c.Segment.ExplicitOrTypedDimensionDomains.Any(dd => dd.DimensionType == SBRExplicitOrTypedDimensionDomain_Type.EXPLICIT && dd.Dimension.EndsWith("}RelativePeriodDurationDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}Y0Minus1")) )));
            Dictionary<string, IList<SBRElement>> sbrPopulatedRPY0Minus1ElementsMap = new Dictionary<string, IList<SBRElement>>();
            if (sbrRPY0Minus1Contexts != null && sbrRPY0Minus1Contexts.Count() > 0)
            {
                sbrRPY0Minus1Context = sbrRPY0Minus1Contexts.First();
        
                report.RPY0Minus1Id = sbrRPY0Minus1Context.Id;
                report.RPY0Minus1Identifier = sbrRPY0Minus1Context.EntityIdentifier;
                report.RPY0Minus1IdentifierScheme = sbrRPY0Minus1Context.EntityScheme;
        
                report.RPY0Minus1Count = sbrRPY0Minus1Contexts.Count();
                report.RPY0Minus1Exists = true;
                report.RPY0Minus1OccurrenceIndex = Array.IndexOf(contextArray, sbrRPY0Minus1Context) + 1;
                report.RPY0Minus1LastOccurrenceIndex = Array.IndexOf(contextArray, sbrRPY0Minus1Contexts.Last()) + 1;
        

                if (report.RPY0Minus1IdentifierScheme == "http://www.ato.gov.au/tfn") report.RPY0Minus1IdentifierTFN = report.RPY0Minus1Identifier;
    
                report.RPY0Minus1StartDate = ((SBRDurationPeriod)sbrRPY0Minus1Context.Period).DurationStartAsDateObject;
                report.RPY0Minus1EndDate = ((SBRDurationPeriod)sbrRPY0Minus1Context.Period).DurationEndAsDateObject;
        
                sbrPopulatedRPY0Minus1ElementsMap = new System.Collections.Generic.Dictionary<string, IList<SBRElement>>();
                for (int i = 0; i < sbrRPY0Minus1Contexts.Count(); i++)
                {
                    sbrRPY0Minus1Context = sbrRPY0Minus1Contexts.ElementAt(i);
            
                    IList<SBRElement> elements = sbrDocument.ElementsByContextId[sbrRPY0Minus1Context.Id];
                    if (elements != null)
                    {
                        for (int e = 0; e < elements.Count(); e++)
                        {
                            SBRElement currentElement = elements[e];
                            if (currentElement == null || currentElement.IsInTuple) continue; // Don't add tuple elements here, they will be found through a different map.
                            if (sbrPopulatedRPY0Minus1ElementsMap.ContainsKey("{" + currentElement.Namespace + "}" + currentElement.Name))
                            {
                                sbrPopulatedRPY0Minus1ElementsMap["{" + currentElement.Namespace + "}" + currentElement.Name].Add(currentElement);
                            }
                            else
                            {
                                sbrPopulatedRPY0Minus1ElementsMap.Add("{" + currentElement.Namespace + "}" + currentElement.Name, new List<SBRElement> { currentElement } );
                            }
                        }
                    }
            
                    if (sbrPopulatedRPY0Minus1ElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.TransferredContinuityTestFail.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS40 = decimal.Parse(currentValues[0].Value);
                    }
                } 
            } 
            #endregion End of Context sbrRPY0Minus1Context
    
            #region sbrRPY0Minus2Context
            IEnumerable<SBRContext> sbrRPY0Minus2Contexts = null;
            SBRContext sbrRPY0Minus2Context = null;
    
            sbrRPY0Minus2Contexts = contextArray.Where(
                c => c.Period != null && c.Period.PeriodType == SBRPeriod_PeriodType.DURATION &&
                c.Segment != null && c.Segment.ExplicitOrTypedDimensionDomains.Count == 2 && 
                (c.Segment.ExplicitOrTypedDimensionDomains.Any(dd => dd.DimensionType == SBRExplicitOrTypedDimensionDomain_Type.EXPLICIT && dd.Dimension.EndsWith("}ReportPartyTypeDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}ReportingParty"))  && 
                (c.Segment.ExplicitOrTypedDimensionDomains.Any(dd => dd.DimensionType == SBRExplicitOrTypedDimensionDomain_Type.EXPLICIT && dd.Dimension.EndsWith("}RelativePeriodDurationDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}Y0Minus2")) )));
            Dictionary<string, IList<SBRElement>> sbrPopulatedRPY0Minus2ElementsMap = new Dictionary<string, IList<SBRElement>>();
            if (sbrRPY0Minus2Contexts != null && sbrRPY0Minus2Contexts.Count() > 0)
            {
                sbrRPY0Minus2Context = sbrRPY0Minus2Contexts.First();
        
                report.RPY0Minus2Id = sbrRPY0Minus2Context.Id;
                report.RPY0Minus2Identifier = sbrRPY0Minus2Context.EntityIdentifier;
                report.RPY0Minus2IdentifierScheme = sbrRPY0Minus2Context.EntityScheme;
        
                report.RPY0Minus2Count = sbrRPY0Minus2Contexts.Count();
                report.RPY0Minus2Exists = true;
                report.RPY0Minus2OccurrenceIndex = Array.IndexOf(contextArray, sbrRPY0Minus2Context) + 1;
                report.RPY0Minus2LastOccurrenceIndex = Array.IndexOf(contextArray, sbrRPY0Minus2Contexts.Last()) + 1;
        

                if (report.RPY0Minus2IdentifierScheme == "http://www.ato.gov.au/tfn") report.RPY0Minus2IdentifierTFN = report.RPY0Minus2Identifier;
    
                report.RPY0Minus2StartDate = ((SBRDurationPeriod)sbrRPY0Minus2Context.Period).DurationStartAsDateObject;
                report.RPY0Minus2EndDate = ((SBRDurationPeriod)sbrRPY0Minus2Context.Period).DurationEndAsDateObject;
        
                sbrPopulatedRPY0Minus2ElementsMap = new System.Collections.Generic.Dictionary<string, IList<SBRElement>>();
                for (int i = 0; i < sbrRPY0Minus2Contexts.Count(); i++)
                {
                    sbrRPY0Minus2Context = sbrRPY0Minus2Contexts.ElementAt(i);
            
                    IList<SBRElement> elements = sbrDocument.ElementsByContextId[sbrRPY0Minus2Context.Id];
                    if (elements != null)
                    {
                        for (int e = 0; e < elements.Count(); e++)
                        {
                            SBRElement currentElement = elements[e];
                            if (currentElement == null || currentElement.IsInTuple) continue; // Don't add tuple elements here, they will be found through a different map.
                            if (sbrPopulatedRPY0Minus2ElementsMap.ContainsKey("{" + currentElement.Namespace + "}" + currentElement.Name))
                            {
                                sbrPopulatedRPY0Minus2ElementsMap["{" + currentElement.Namespace + "}" + currentElement.Name].Add(currentElement);
                            }
                            else
                            {
                                sbrPopulatedRPY0Minus2ElementsMap.Add("{" + currentElement.Namespace + "}" + currentElement.Name, new List<SBRElement> { currentElement } );
                            }
                        }
                    }
            
                    if (sbrPopulatedRPY0Minus2ElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.TransferredContinuityTestFail.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS41 = decimal.Parse(currentValues[0].Value);
                    }
                } 
            } 
            #endregion End of Context sbrRPY0Minus2Context
    
            #region sbrRPY0Minus3Context
            IEnumerable<SBRContext> sbrRPY0Minus3Contexts = null;
            SBRContext sbrRPY0Minus3Context = null;
    
            sbrRPY0Minus3Contexts = contextArray.Where(
                c => c.Period != null && c.Period.PeriodType == SBRPeriod_PeriodType.DURATION &&
                c.Segment != null && c.Segment.ExplicitOrTypedDimensionDomains.Count == 2 && 
                (c.Segment.ExplicitOrTypedDimensionDomains.Any(dd => dd.DimensionType == SBRExplicitOrTypedDimensionDomain_Type.EXPLICIT && dd.Dimension.EndsWith("}ReportPartyTypeDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}ReportingParty"))  && 
                (c.Segment.ExplicitOrTypedDimensionDomains.Any(dd => dd.DimensionType == SBRExplicitOrTypedDimensionDomain_Type.EXPLICIT && dd.Dimension.EndsWith("}RelativePeriodDurationDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}Y0Minus3")) )));
            Dictionary<string, IList<SBRElement>> sbrPopulatedRPY0Minus3ElementsMap = new Dictionary<string, IList<SBRElement>>();
            if (sbrRPY0Minus3Contexts != null && sbrRPY0Minus3Contexts.Count() > 0)
            {
                sbrRPY0Minus3Context = sbrRPY0Minus3Contexts.First();
        
                report.RPY0Minus3Id = sbrRPY0Minus3Context.Id;
                report.RPY0Minus3Identifier = sbrRPY0Minus3Context.EntityIdentifier;
                report.RPY0Minus3IdentifierScheme = sbrRPY0Minus3Context.EntityScheme;
        
                report.RPY0Minus3Count = sbrRPY0Minus3Contexts.Count();
                report.RPY0Minus3Exists = true;
                report.RPY0Minus3OccurrenceIndex = Array.IndexOf(contextArray, sbrRPY0Minus3Context) + 1;
                report.RPY0Minus3LastOccurrenceIndex = Array.IndexOf(contextArray, sbrRPY0Minus3Contexts.Last()) + 1;
        

                if (report.RPY0Minus3IdentifierScheme == "http://www.ato.gov.au/tfn") report.RPY0Minus3IdentifierTFN = report.RPY0Minus3Identifier;
    
                report.RPY0Minus3StartDate = ((SBRDurationPeriod)sbrRPY0Minus3Context.Period).DurationStartAsDateObject;
                report.RPY0Minus3EndDate = ((SBRDurationPeriod)sbrRPY0Minus3Context.Period).DurationEndAsDateObject;
        
                sbrPopulatedRPY0Minus3ElementsMap = new System.Collections.Generic.Dictionary<string, IList<SBRElement>>();
                for (int i = 0; i < sbrRPY0Minus3Contexts.Count(); i++)
                {
                    sbrRPY0Minus3Context = sbrRPY0Minus3Contexts.ElementAt(i);
            
                    IList<SBRElement> elements = sbrDocument.ElementsByContextId[sbrRPY0Minus3Context.Id];
                    if (elements != null)
                    {
                        for (int e = 0; e < elements.Count(); e++)
                        {
                            SBRElement currentElement = elements[e];
                            if (currentElement == null || currentElement.IsInTuple) continue; // Don't add tuple elements here, they will be found through a different map.
                            if (sbrPopulatedRPY0Minus3ElementsMap.ContainsKey("{" + currentElement.Namespace + "}" + currentElement.Name))
                            {
                                sbrPopulatedRPY0Minus3ElementsMap["{" + currentElement.Namespace + "}" + currentElement.Name].Add(currentElement);
                            }
                            else
                            {
                                sbrPopulatedRPY0Minus3ElementsMap.Add("{" + currentElement.Namespace + "}" + currentElement.Name, new List<SBRElement> { currentElement } );
                            }
                        }
                    }
            
                    if (sbrPopulatedRPY0Minus3ElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.TransferredContinuityTestFail.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS42 = decimal.Parse(currentValues[0].Value);
                    }
                } 
            } 
            #endregion End of Context sbrRPY0Minus3Context
    
            #region sbrRPY0Minus4PContext
            IEnumerable<SBRContext> sbrRPY0Minus4PContexts = null;
            SBRContext sbrRPY0Minus4PContext = null;
    
            sbrRPY0Minus4PContexts = contextArray.Where(
                c => c.Period != null && c.Period.PeriodType == SBRPeriod_PeriodType.DURATION &&
                c.Segment != null && c.Segment.ExplicitOrTypedDimensionDomains.Count == 2 && 
                (c.Segment.ExplicitOrTypedDimensionDomains.Any(dd => dd.DimensionType == SBRExplicitOrTypedDimensionDomain_Type.EXPLICIT && dd.Dimension.EndsWith("}ReportPartyTypeDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}ReportingParty"))  && 
                (c.Segment.ExplicitOrTypedDimensionDomains.Any(dd => dd.DimensionType == SBRExplicitOrTypedDimensionDomain_Type.EXPLICIT && dd.Dimension.EndsWith("}RelativePeriodDurationDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}Y0Minus4Plus")) )));
            Dictionary<string, IList<SBRElement>> sbrPopulatedRPY0Minus4PElementsMap = new Dictionary<string, IList<SBRElement>>();
            if (sbrRPY0Minus4PContexts != null && sbrRPY0Minus4PContexts.Count() > 0)
            {
                sbrRPY0Minus4PContext = sbrRPY0Minus4PContexts.First();
        
                report.RPY0Minus4PId = sbrRPY0Minus4PContext.Id;
                report.RPY0Minus4PIdentifier = sbrRPY0Minus4PContext.EntityIdentifier;
                report.RPY0Minus4PIdentifierScheme = sbrRPY0Minus4PContext.EntityScheme;
        
                report.RPY0Minus4PCount = sbrRPY0Minus4PContexts.Count();
                report.RPY0Minus4PExists = true;
                report.RPY0Minus4POccurrenceIndex = Array.IndexOf(contextArray, sbrRPY0Minus4PContext) + 1;
                report.RPY0Minus4PLastOccurrenceIndex = Array.IndexOf(contextArray, sbrRPY0Minus4PContexts.Last()) + 1;
        

                if (report.RPY0Minus4PIdentifierScheme == "http://www.ato.gov.au/tfn") report.RPY0Minus4PIdentifierTFN = report.RPY0Minus4PIdentifier;
    
                report.RPY0Minus4PStartDate = ((SBRDurationPeriod)sbrRPY0Minus4PContext.Period).DurationStartAsDateObject;
                report.RPY0Minus4PEndDate = ((SBRDurationPeriod)sbrRPY0Minus4PContext.Period).DurationEndAsDateObject;
        
                sbrPopulatedRPY0Minus4PElementsMap = new System.Collections.Generic.Dictionary<string, IList<SBRElement>>();
                for (int i = 0; i < sbrRPY0Minus4PContexts.Count(); i++)
                {
                    sbrRPY0Minus4PContext = sbrRPY0Minus4PContexts.ElementAt(i);
            
                    IList<SBRElement> elements = sbrDocument.ElementsByContextId[sbrRPY0Minus4PContext.Id];
                    if (elements != null)
                    {
                        for (int e = 0; e < elements.Count(); e++)
                        {
                            SBRElement currentElement = elements[e];
                            if (currentElement == null || currentElement.IsInTuple) continue; // Don't add tuple elements here, they will be found through a different map.
                            if (sbrPopulatedRPY0Minus4PElementsMap.ContainsKey("{" + currentElement.Namespace + "}" + currentElement.Name))
                            {
                                sbrPopulatedRPY0Minus4PElementsMap["{" + currentElement.Namespace + "}" + currentElement.Name].Add(currentElement);
                            }
                            else
                            {
                                sbrPopulatedRPY0Minus4PElementsMap.Add("{" + currentElement.Namespace + "}" + currentElement.Name, new List<SBRElement> { currentElement } );
                            }
                        }
                    }
            
                    if (sbrPopulatedRPY0Minus4PElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}Tax.Losses.TransferredContinuityTestFail.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CGLS43 = decimal.Parse(currentValues[0].Value);
                    }
                } 
            } 
            #endregion End of Context sbrRPY0Minus4PContext
            return report;

        } // Of Consume Method
        #region ValidateRPOrganisationNameDetailsCollection
        protected virtual void ValidateRPOrganisationNameDetailsCollection(List<ProcessMessageDocument> errors, IEnumerable<SBRElement> tupleCollection, IEnumerable<SBRContext> contexts, CGLS2017 report)
        {
            bool assertion;
            ProcessMessageDocument processMessage;
            ProcessMessageParameter parameter;
            HashSet<string> alreadyChecked = new HashSet<string>();

            if (tupleCollection != null)
            {
                foreach (SBRElement tupleElement in tupleCollection)
                {
                    //Only check this for the RP Context exit out otherwise
                     if (tupleElement.ChildElements == null || tupleElement.ChildElements.Count == 0 || contexts == null || !contexts.Contains(tupleElement.ChildElements[0].Context))
                        continue;

                    IDictionary<string, SBRElement> tupleElementMap = tupleElement.PopulatedChildElementsMap;

                    SBRElement CGLS100Value = null;
                    string CGLS100 = null;
                    SBRElement CGLS2Value = null;
                    string CGLS2 = null;

                    if (tupleElementMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}OrganisationNameDetails.OrganisationalNameType.Code", out CGLS100Value))
                    {
                        if (!CGLS100Value.IsNil) CGLS100 = CGLS100Value.Value;
                    }

                    if (tupleElementMap.TryGetValue("{http://www.sbr.gov.au/ato/cgls}OrganisationNameDetails.OrganisationalName.Text", out CGLS2Value))
                    {
                        if (!CGLS2Value.IsNil) CGLS2 = CGLS2Value.Value;
                    }
        
                    #region VR.ATO.GEN.410049

        /*  VR.ATO.GEN.410049
            Organisation Name Type Code must be 'MN'

        Legacy Rule Format:
            IF (pyde.xx.xx:OrganisationNameDetails.OrganisationalNameType.Code <> NULLORBLANK) AND (pyde.xx.xx:OrganisationNameDetails.OrganisationalNameType.Code <> "MN")
               RETURN VALIDATION MESSAGE
            ENDIF
    
        Technical Business Rule Format:
            (^CGLS100 <> BLANK) AND (^CGLS100 <> 'MN')

        Data Elements:
    
            RP:^CGLS100 = pyde.02.00:OrganisationNameDetails.OrganisationalNameType.Code WHERE [OrganisationNameDetails.OrganisationalNameType.Code='MN']
            */
                    assertion = (string.IsNullOrWhiteSpace(CGLS100) != true && CGLS100 != @"MN");
                    if (assertion)
                    {
                        processMessage = new ProcessMessageDocument()
                        {
                            Code = "CMN.ATO.GEN.410049", Severity = ProcessMessageSeverity.Error,
                            Description = @"Organisation Name Type Code must be 'MN'",
                            Location = CGLS100Value == null ? DeriveSbrElementLocation(tupleElement, true) + "/tns:OrganisationNameDetails.OrganisationalNameType.Code" : DeriveSbrElementLocation(CGLS100Value),
                            Parameters = new ProcessMessageParameters() { new ProcessMessageParameter() {Name = "RuleIdentifier", Value = "VR.ATO.GEN.410049"} },
                        };
                    processMessage.Parameters.Add(new ProcessMessageParameter
                        { Name = "CGLS100", Value = CGLS100 });
        
                        errors.Add(processMessage);
                    }
                    #endregion
                }
            }
        }
        #endregion

    } // Of Class
} // Of Namespace