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

namespace Ato.EN.IntegrationServices.CodeGenerationCHTWTHHLDTFN
{
    public class CHTWTHHLD2018Consumer
    {

        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 CHTWTHHLD2018 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 CHTWTHHLD2018 Consume(SBRDocument sbrDocument, bool validationMode, out List<ProcessMessageDocument> errors)
        {
            CHTWTHHLD2018 report;
            report = new CHTWTHHLD2018();
            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 occurrences 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.CHTWTHHLD55 = report.RPStartDate;
                    report.CHTWTHHLD56 = report.RPEndDate;
                    report.CHTWTHHLD68 = report.RPIdentifier;
            
                    if (sbrPopulatedRPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}OrganisationNameDetails.OrganisationalName.Text", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD2 = currentValues[0].Value;
                    }
            
                    if (sbrPopulatedRPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}Identifiers.AustralianBusinessNumber.Identifier", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD80 = currentValues[0].Value;
                    }
            
                    if (sbrPopulatedRPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}IncomeTax.PayAsYouGoWithholding.TaxWithheld.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD10 = decimal.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}IncomeTax.PayAsYouGoWithholding.PaymentGross.Amount", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD9 = decimal.Parse(currentValues[0].Value);
                    }
                } 
            } 
            #endregion End of Context sbrRPContext
    
            #region sbrRPPostalContext
            IEnumerable<SBRContext> sbrRPPostalContexts = null;
            SBRContext sbrRPPostalContext = null;
    
            sbrRPPostalContexts = 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("}AddressUsageDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}POS")) )));
            Dictionary<string, IList<SBRElement>> sbrPopulatedRPPostalElementsMap = new Dictionary<string, IList<SBRElement>>();
            if (sbrRPPostalContexts != null && sbrRPPostalContexts.Count() > 0)
            {
                sbrRPPostalContext = sbrRPPostalContexts.First();
        
                report.RPPostalId = sbrRPPostalContext.Id;
                report.RPPostalIdentifier = sbrRPPostalContext.EntityIdentifier;
                report.RPPostalIdentifierScheme = sbrRPPostalContext.EntityScheme;
        
                report.RPPostalCount = sbrRPPostalContexts.Count();
                report.RPPostalExists = true;
                report.RPPostalOccurrenceIndex = Array.IndexOf(contextArray, sbrRPPostalContext) + 1;
                report.RPPostalLastOccurrenceIndex = Array.IndexOf(contextArray, sbrRPPostalContexts.Last()) + 1;
        

                if (report.RPPostalIdentifierScheme == "http://www.ato.gov.au/tfn") report.RPPostalIdentifierTFN = report.RPPostalIdentifier;
    
                report.RPPostalStartDate = ((SBRDurationPeriod)sbrRPPostalContext.Period).DurationStartAsDateObject;
                report.RPPostalEndDate = ((SBRDurationPeriod)sbrRPPostalContext.Period).DurationEndAsDateObject;
        
                sbrPopulatedRPPostalElementsMap = new System.Collections.Generic.Dictionary<string, IList<SBRElement>>();
                for (int i = 0; i < sbrRPPostalContexts.Count(); i++)
                {
                    sbrRPPostalContext = sbrRPPostalContexts.ElementAt(i);
            
                    IList<SBRElement> elements = sbrDocument.ElementsByContextId[sbrRPPostalContext.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 (sbrPopulatedRPPostalElementsMap.ContainsKey("{" + currentElement.Namespace + "}" + currentElement.Name))
                            {
                                sbrPopulatedRPPostalElementsMap["{" + currentElement.Namespace + "}" + currentElement.Name].Add(currentElement);
                            }
                            else
                            {
                                sbrPopulatedRPPostalElementsMap.Add("{" + currentElement.Namespace + "}" + currentElement.Name, new List<SBRElement> { currentElement } );
                            }
                        }
                    }
            
                    if (sbrPopulatedRPPostalElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}AddressDetails.Line1.Text", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD3 = currentValues[0].Value;
                    }
            
                    if (sbrPopulatedRPPostalElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}AddressDetails.Line2.Text", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD4 = currentValues[0].Value;
                    }
            
                    if (sbrPopulatedRPPostalElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}AddressDetails.LocalityName.Text", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD5 = currentValues[0].Value;
                    }
            
                    if (sbrPopulatedRPPostalElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}AddressDetails.StateOrTerritory.Code", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD6 = currentValues[0].Value;
                    }
            
                    if (sbrPopulatedRPPostalElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}AddressDetails.Postcode.Text", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD7 = currentValues[0].Value;
                    }
            
                    if (sbrPopulatedRPPostalElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}AddressDetails.Country.Code", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD8 = currentValues[0].Value;
                    }
                } 
            } 
            #endregion End of Context sbrRPPostalContext
    
            #region sbrTrusteeContext
            IEnumerable<SBRContext> sbrTrusteeContexts = null;
            SBRContext sbrTrusteeContext = null;
    
            sbrTrusteeContexts = 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("}Trustee")) ));
            Dictionary<string, IList<SBRElement>> sbrPopulatedTrusteeElementsMap = new Dictionary<string, IList<SBRElement>>();
            if (sbrTrusteeContexts != null && sbrTrusteeContexts.Count() > 0)
            {
                sbrTrusteeContext = sbrTrusteeContexts.First();
        
                report.TrusteeId = sbrTrusteeContext.Id;
                report.TrusteeIdentifier = sbrTrusteeContext.EntityIdentifier;
                report.TrusteeIdentifierScheme = sbrTrusteeContext.EntityScheme;
        
                report.TrusteeCount = sbrTrusteeContexts.Count();
                report.TrusteeExists = true;
                report.TrusteeOccurrenceIndex = Array.IndexOf(contextArray, sbrTrusteeContext) + 1;
                report.TrusteeLastOccurrenceIndex = Array.IndexOf(contextArray, sbrTrusteeContexts.Last()) + 1;
        

                if (report.TrusteeIdentifierScheme == "http://www.sbr.gov.au/id") report.TrusteeIdentifierID = report.TrusteeIdentifier;
    
                report.TrusteeStartDate = ((SBRDurationPeriod)sbrTrusteeContext.Period).DurationStartAsDateObject;
                report.TrusteeEndDate = ((SBRDurationPeriod)sbrTrusteeContext.Period).DurationEndAsDateObject;
        
                sbrPopulatedTrusteeElementsMap = new System.Collections.Generic.Dictionary<string, IList<SBRElement>>();
                for (int i = 0; i < sbrTrusteeContexts.Count(); i++)
                {
                    sbrTrusteeContext = sbrTrusteeContexts.ElementAt(i);
            
                    IList<SBRElement> elements = sbrDocument.ElementsByContextId[sbrTrusteeContext.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 (sbrPopulatedTrusteeElementsMap.ContainsKey("{" + currentElement.Namespace + "}" + currentElement.Name))
                            {
                                sbrPopulatedTrusteeElementsMap["{" + currentElement.Namespace + "}" + currentElement.Name].Add(currentElement);
                            }
                            else
                            {
                                sbrPopulatedTrusteeElementsMap.Add("{" + currentElement.Namespace + "}" + currentElement.Name, new List<SBRElement> { currentElement } );
                            }
                        }
                    }
            
                    if (sbrPopulatedTrusteeElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}ElectronicContact.Telephone.Area.Code", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD18 = currentValues[0].Value;
                    }
            
                    if (sbrPopulatedTrusteeElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}ElectronicContact.Telephone.Minimal.Number", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD19 = currentValues[0].Value;
                    }
            
                    if (sbrPopulatedTrusteeElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}PersonNameDetails.Title.Text", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD11 = currentValues[0].Value;
                    }
            
                    if (sbrPopulatedTrusteeElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}PersonNameDetails.FamilyName.Text", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD12 = currentValues[0].Value;
                    }
            
                    if (sbrPopulatedTrusteeElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}PersonNameDetails.NameSuffix.Text", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD13 = currentValues[0].Value;
                    }
            
                    if (sbrPopulatedTrusteeElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}PersonNameDetails.GivenName.Text", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD14 = currentValues[0].Value;
                    }
            
                    if (sbrPopulatedTrusteeElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}PersonNameDetails.OtherGivenName.Text", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD15 = currentValues[0].Value;
                    }
            
                    if (sbrPopulatedTrusteeElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}OrganisationNameDetails.OrganisationalName.Text", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD16 = currentValues[0].Value;
                    }
            
                    if (sbrPopulatedTrusteeElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}Identifiers.AustralianBusinessNumber.Identifier", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD17 = currentValues[0].Value;
                    }
                } 
            } 
            #endregion End of Context sbrTrusteeContext
    
            #region sbrINTTrueAndCorrectContext
            IEnumerable<SBRContext> sbrINTTrueAndCorrectContexts = null;
            SBRContext sbrINTTrueAndCorrectContext = null;
    
            sbrINTTrueAndCorrectContexts = 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("}Intermediary"))  && 
                (c.Segment.ExplicitOrTypedDimensionDomains.Any(dd => dd.DimensionType == SBRExplicitOrTypedDimensionDomain_Type.EXPLICIT && dd.Dimension.EndsWith("}DeclarationTypeDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}TrueAndCorrect")) )));
            Dictionary<string, IList<SBRElement>> sbrPopulatedINTTrueAndCorrectElementsMap = new Dictionary<string, IList<SBRElement>>();
            if (sbrINTTrueAndCorrectContexts != null && sbrINTTrueAndCorrectContexts.Count() > 0)
            {
                sbrINTTrueAndCorrectContext = sbrINTTrueAndCorrectContexts.First();
        
                report.INTTrueAndCorrectId = sbrINTTrueAndCorrectContext.Id;
                report.INTTrueAndCorrectIdentifier = sbrINTTrueAndCorrectContext.EntityIdentifier;
                report.INTTrueAndCorrectIdentifierScheme = sbrINTTrueAndCorrectContext.EntityScheme;
        
                report.INTTrueAndCorrectCount = sbrINTTrueAndCorrectContexts.Count();
                report.INTTrueAndCorrectExists = true;
                report.INTTrueAndCorrectOccurrenceIndex = Array.IndexOf(contextArray, sbrINTTrueAndCorrectContext) + 1;
                report.INTTrueAndCorrectLastOccurrenceIndex = Array.IndexOf(contextArray, sbrINTTrueAndCorrectContexts.Last()) + 1;
        

                if (report.INTTrueAndCorrectIdentifierScheme == "http://www.abr.gov.au/abn") report.INTTrueAndCorrectIdentifierABN = report.INTTrueAndCorrectIdentifier;
    
                report.INTTrueAndCorrectStartDate = ((SBRDurationPeriod)sbrINTTrueAndCorrectContext.Period).DurationStartAsDateObject;
                report.INTTrueAndCorrectEndDate = ((SBRDurationPeriod)sbrINTTrueAndCorrectContext.Period).DurationEndAsDateObject;
        
                sbrPopulatedINTTrueAndCorrectElementsMap = new System.Collections.Generic.Dictionary<string, IList<SBRElement>>();
                for (int i = 0; i < sbrINTTrueAndCorrectContexts.Count(); i++)
                {
                    sbrINTTrueAndCorrectContext = sbrINTTrueAndCorrectContexts.ElementAt(i);
            
                    IList<SBRElement> elements = sbrDocument.ElementsByContextId[sbrINTTrueAndCorrectContext.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 (sbrPopulatedINTTrueAndCorrectElementsMap.ContainsKey("{" + currentElement.Namespace + "}" + currentElement.Name))
                            {
                                sbrPopulatedINTTrueAndCorrectElementsMap["{" + currentElement.Namespace + "}" + currentElement.Name].Add(currentElement);
                            }
                            else
                            {
                                sbrPopulatedINTTrueAndCorrectElementsMap.Add("{" + currentElement.Namespace + "}" + currentElement.Name, new List<SBRElement> { currentElement } );
                            }
                        }
                    }
                    report.CHTWTHHLD83 = report.INTTrueAndCorrectIdentifier;
            
                    if (sbrPopulatedINTTrueAndCorrectElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}PersonUnstructuredName.FullName.Text", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD84 = currentValues[0].Value;
                    }
            
                    if (sbrPopulatedINTTrueAndCorrectElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}PersonNameDetails.Position.Text", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD85 = currentValues[0].Value;
                    }
            
                    if (sbrPopulatedINTTrueAndCorrectElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}ElectronicContact.Telephone.Area.Code", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD86 = currentValues[0].Value;
                    }
            
                    if (sbrPopulatedINTTrueAndCorrectElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}ElectronicContact.Telephone.Minimal.Number", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD87 = currentValues[0].Value;
                    }
            
                    if (sbrPopulatedINTTrueAndCorrectElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}Identifiers.TaxAgentNumber.Identifier", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD88 = currentValues[0].Value;
                    }
            
                    if (sbrPopulatedINTTrueAndCorrectElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}Declaration.Signature.Date", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD89 = DateTime.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedINTTrueAndCorrectElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}Declaration.StatementAccepted.Indicator", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD90 = ToBoolean(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedINTTrueAndCorrectElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}Declaration.SignatoryIdentifier.Text", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD91 = currentValues[0].Value;
                    }
                } 
            } 
            #endregion End of Context sbrINTTrueAndCorrectContext
    
            #region sbrRPTrueAndCorrectContext
            IEnumerable<SBRContext> sbrRPTrueAndCorrectContexts = null;
            SBRContext sbrRPTrueAndCorrectContext = null;
    
            sbrRPTrueAndCorrectContexts = 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("}DeclarationTypeDimension") && ((SBRExplicitDimensionDomain)dd).Domain.EndsWith("}TrueAndCorrect")) )));
            Dictionary<string, IList<SBRElement>> sbrPopulatedRPTrueAndCorrectElementsMap = new Dictionary<string, IList<SBRElement>>();
            if (sbrRPTrueAndCorrectContexts != null && sbrRPTrueAndCorrectContexts.Count() > 0)
            {
                sbrRPTrueAndCorrectContext = sbrRPTrueAndCorrectContexts.First();
        
                report.RPTrueAndCorrectId = sbrRPTrueAndCorrectContext.Id;
                report.RPTrueAndCorrectIdentifier = sbrRPTrueAndCorrectContext.EntityIdentifier;
                report.RPTrueAndCorrectIdentifierScheme = sbrRPTrueAndCorrectContext.EntityScheme;
        
                report.RPTrueAndCorrectCount = sbrRPTrueAndCorrectContexts.Count();
                report.RPTrueAndCorrectExists = true;
                report.RPTrueAndCorrectOccurrenceIndex = Array.IndexOf(contextArray, sbrRPTrueAndCorrectContext) + 1;
                report.RPTrueAndCorrectLastOccurrenceIndex = Array.IndexOf(contextArray, sbrRPTrueAndCorrectContexts.Last()) + 1;
        

                if (report.RPTrueAndCorrectIdentifierScheme == "http://www.ato.gov.au/tfn") report.RPTrueAndCorrectIdentifierTFN = report.RPTrueAndCorrectIdentifier;
    
                report.RPTrueAndCorrectStartDate = ((SBRDurationPeriod)sbrRPTrueAndCorrectContext.Period).DurationStartAsDateObject;
                report.RPTrueAndCorrectEndDate = ((SBRDurationPeriod)sbrRPTrueAndCorrectContext.Period).DurationEndAsDateObject;
        
                sbrPopulatedRPTrueAndCorrectElementsMap = new System.Collections.Generic.Dictionary<string, IList<SBRElement>>();
                for (int i = 0; i < sbrRPTrueAndCorrectContexts.Count(); i++)
                {
                    sbrRPTrueAndCorrectContext = sbrRPTrueAndCorrectContexts.ElementAt(i);
            
                    IList<SBRElement> elements = sbrDocument.ElementsByContextId[sbrRPTrueAndCorrectContext.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 (sbrPopulatedRPTrueAndCorrectElementsMap.ContainsKey("{" + currentElement.Namespace + "}" + currentElement.Name))
                            {
                                sbrPopulatedRPTrueAndCorrectElementsMap["{" + currentElement.Namespace + "}" + currentElement.Name].Add(currentElement);
                            }
                            else
                            {
                                sbrPopulatedRPTrueAndCorrectElementsMap.Add("{" + currentElement.Namespace + "}" + currentElement.Name, new List<SBRElement> { currentElement } );
                            }
                        }
                    }
                    report.CHTWTHHLD82 = report.RPTrueAndCorrectIdentifier;
            
                    if (sbrPopulatedRPTrueAndCorrectElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}PersonUnstructuredName.FullName.Text", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD73 = currentValues[0].Value;
                    }
            
                    if (sbrPopulatedRPTrueAndCorrectElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}PersonNameDetails.Position.Text", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD74 = currentValues[0].Value;
                    }
            
                    if (sbrPopulatedRPTrueAndCorrectElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}ElectronicContact.Telephone.Area.Code", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD75 = currentValues[0].Value;
                    }
            
                    if (sbrPopulatedRPTrueAndCorrectElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}ElectronicContact.Telephone.Minimal.Number", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD79 = currentValues[0].Value;
                    }
            
                    if (sbrPopulatedRPTrueAndCorrectElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}Identifiers.TaxAgentNumber.Identifier", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD76 = currentValues[0].Value;
                    }
            
                    if (sbrPopulatedRPTrueAndCorrectElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}Declaration.Signature.Date", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD77 = DateTime.Parse(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPTrueAndCorrectElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}Declaration.StatementAccepted.Indicator", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD78 = ToBoolean(currentValues[0].Value);
                    }
            
                    if (sbrPopulatedRPTrueAndCorrectElementsMap.TryGetValue("{http://www.sbr.gov.au/ato/chtwthhld}Declaration.SignatoryIdentifier.Text", out currentValues))
                    {
                        if (!currentValues[0].IsNil) report.CHTWTHHLD81 = currentValues[0].Value;
                    }
                } 
            } 
            #endregion End of Context sbrRPTrueAndCorrectContext
            return report;

        } // Of Consume Method
    } // Of Class
} // Of Namespace
