:arrow_up: Migrate japan core module.

:arrow_up: Migrate japan core module.

jsoniq version "1.0";
module namespace japan = "http://28.io/modules/xbrl/profiles/japan/core";

import module namespace mw = "http://28.io/modules/xbrl/data-source-wrapper";
import module namespace es = "http://28.io/modules/elasticsearch";

import module namespace config = "http://apps.28.io/config";

import module namespace archives = "http://28.io/modules/xbrl/archives";
import module namespace entities = "http://28.io/modules/xbrl/entities";

(:
 : Copyright 2012-2015 28msec Inc.
 :)
(:~
 :
This module provides functionality for querying against the Japan profile.

 :
 : @author Ghislain Fourny
 :
 :)

(:~
 :
Retrieves the entities with the given identifiers.

 :
 : @param $edinetcode a sequence of edinet codes like E01225.
 : @param $securitiescode a sequence of securities codes, like 9432.
 : @param $eid a sequence of raw EIDs.
 : @param $tag a sequence of tags (e.g., indices).
 : @param $full-text a full text search phrase
 : @param $language a language identifier for the full text search (e.g. ja/en)
 : @param $options optional settings such as full-text-offset or full-text-limit
 :
 : @return the entities that match those identifiers.
 :)
declare %an:nondeterministic function japan:entities(
    $edinetcode as string*,
    $securitiescode as string*,
    $eid as string*,
    $tag as string*,
    $full-text as string?,
    $language as string,
    $aid as string*,
    $options as object?
) as object*
{
    switch(true)
    case $tag = "ALL" return entities:entities()
    case exists(($eid, $edinetcode, $securitiescode, $tag, $full-text)) return
       for $entity in (
         mw:find($entities:col, { "Profiles" : { "FSA" : { "Tags" : [ $tag ] } } }),

         mw:find($entities:col, { "Profiles" : { "FSA" : { "EDINETCode" : [ $edinetcode ] } } }),

         mw:find($entities:col, { "Profiles" : { "FSA" : { "SecuritiesCode" : [ $securitiescode ] } } }),

         let $conn := es:connection("xbrl")
         where exists($full-text)
         return es:search(
           $conn,
           $config:query-db.db,
           "entities",
           {
             "from" : ($options.full-text-offset, 0)[1],
             "size" : ($options.full-text-limit, 10)[1],
             "query" : {
               "multi_match" : {
                 "query": $full-text,
                 "type": "most_fields",
                 "fields": [
                   switch($language)
                   case "ja" return
                     ("SubmitterName", "FundName", "IssuerName", "Province", "SecuritiesType")
                   default return ("SubmitterNameAlphabetic","Industry")
                 ]
               }
             }
           }
         ).hits.hits[]._source,

         entities:entities(($eid, archives:archives($aid).Entity))

       )
       group by $entity._id
       return $entity[1]
    default return ()
};

(:~
 :
Retrieves the filings with the given characteristics.

 :
 : @param $entities a sequence of entities or EIDs.
 : @param $fiscalYear a sequence of fiscal years.
 : @param $fiscalPeriod a sequence of fiscal periods.
 : @param $filingKind a sequence of filing kinds to filter for.
 : @param $aid a sequence of AIDs.
 :
 : @return the filings that match those criteria.
 :)
declare function japan:filings(
    $entities as item*,
    $fiscalYear as integer*,
    $fiscalPeriod as string*,
    $filingKind as string*,
    $aid as string*) as object*
{
    archives:archives($aid),
    if($fiscalYear = 1)
    then
        for $a as object in archives:archives-for-entities($entities)
        where empty($filingKind) or $a.Profiles.FSA.FilingKinds[] = $filingKind
        where (empty($fiscalPeriod) or ($fiscalPeriod = "ALL") or
               $a.Profiles.FSA.DocumentFiscalPeriodFocus = $fiscalPeriod)
        group by $a.Entity
        return
            for $filing in $a
            group by $fy := $filing.Profiles.FSA.DocumentFiscalYearFocus
            order by $fy descending
            count $i where $i eq 1
            return $filing
    else
        for $a as object in archives:archives-for-entities($entities)
        where empty($filingKind) or $a.Profiles.FSA.FilingKinds[] = $filingKind
        where (empty($fiscalYear) or
               $fiscalYear = 0 or
               $fiscalYear = $a.Profiles.FSA.DocumentFiscalYearFocus)
               and (empty($fiscalPeriod) or ($fiscalPeriod = "ALL") or
               $a.Profiles.FSA.DocumentFiscalPeriodFocus = $fiscalPeriod)
        return $a
};

(:~
 :
Return latest filings of entities and fiscal periods.

 :
 : @param $profile-name the name of the profile (e.g., SEC, Japan, Generic).
 : @param $entities a sequence of entity objects.
 : @param $fiscal-periods a set of fiscal periods such as "Q1", "Q2", "Q3", "Q4", "FY"
 :
 : @return the latest archives for given entities and fiscal periods.
 :)
declare function japan:latest-filings(
    $entities as object*,
    $fiscal-periods as string*) as object*
{
    (
        error(xs:QName("japan:NOT_IMPLEMENTED"),
            "japan profile: Getting latest-filings for entities not implemented."),

        $entities,
        $fiscal-periods
    )
};

jsoniq version "1.0";
module namespace japan = "http://28.io/modules/xbrl/profiles/japan/core";

import module namespace mw = "http://28.io/modules/xbrl/mongo-wrapper";
import module namespace es = "http://28.io/modules/elasticsearch";

import module namespace config = "http://apps.28.io/config";

import module namespace archives = "http://28.io/modules/xbrl/archives";
import module namespace entities = "http://28.io/modules/xbrl/entities";

(:
 : Copyright 2012-2015 28msec Inc.
 :)
(:~
 :
This module provides functionality for querying against the Japan profile.

 :
 : @author Ghislain Fourny
 :
 :)

(:~
 :
Retrieves the entities with the given identifiers.

 :
 : @param $edinetcode a sequence of edinet codes like E01225.
 : @param $securitiescode a sequence of securities codes, like 9432.
 : @param $eid a sequence of raw EIDs.
 : @param $tag a sequence of tags (e.g., indices).
 : @param $full-text a full text search phrase
 : @param $language a language identifier for the full text search (e.g. ja/en)
 : @param $options optional settings such as full-text-offset or full-text-limit
 :
 : @return the entities that match those identifiers.
 :)
declare %an:nondeterministic function japan:entities(
    $edinetcode as string*,
    $securitiescode as string*,
    $eid as string*,
    $tag as string*,
    $full-text as string?,
    $language as string,
    $aid as string*,
    $options as object?
) as object*
{
    switch(true)
    case $tag = "ALL" return entities:entities()
    case exists(($eid, $edinetcode, $securitiescode, $tag, $full-text)) return
       for $entity in (
         mw:find($entities:col, { "Profiles" : { "FSA" : { "Tags" : [ $tag ] } } }),

         mw:find($entities:col, { "Profiles" : { "FSA" : { "EDINETCode" : [ $edinetcode ] } } }),

         mw:find($entities:col, { "Profiles" : { "FSA" : { "SecuritiesCode" : [ $securitiescode ] } } }),

         let $conn := es:connection("xbrl")
         where exists($full-text)
         return es:search(
           $conn,
           $config:query-db.db,
           "entities",
           {
             "from" : ($options.full-text-offset, 0)[1],
             "size" : ($options.full-text-limit, 10)[1],
             "query" : {
               "multi_match" : {
                 "query": $full-text,
                 "type": "most_fields",
                 "fields": [
                   switch($language)
                   case "ja" return
                     ("SubmitterName", "FundName", "IssuerName", "Province", "SecuritiesType")
                   default return ("SubmitterNameAlphabetic","Industry")
                 ]
               }
             }
           }
         ).hits.hits[]._source,

         entities:entities(($eid, archives:archives($aid).Entity))

       )
       group by $entity._id
       return $entity[1]
    default return ()
};

(:~
 :
Retrieves the filings with the given characteristics.

 :
 : @param $entities a sequence of entities or EIDs.
 : @param $fiscalYear a sequence of fiscal years.
 : @param $fiscalPeriod a sequence of fiscal periods.
 : @param $filingKind a sequence of filing kinds to filter for.
 : @param $aid a sequence of AIDs.
 :
 : @return the filings that match those criteria.
 :)
declare function japan:filings(
    $entities as item*,
    $fiscalYear as integer*,
    $fiscalPeriod as string*,
    $filingKind as string*,
    $aid as string*) as object*
{
    archives:archives($aid),
    if($fiscalYear = 1)
    then
        for $a as object in archives:archives-for-entities($entities)
        where empty($filingKind) or $a.Profiles.FSA.FilingKinds[] = $filingKind
        where (empty($fiscalPeriod) or ($fiscalPeriod = "ALL") or
               $a.Profiles.FSA.DocumentFiscalPeriodFocus = $fiscalPeriod)
        group by $a.Entity
        return
            for $filing in $a
            group by $fy := $filing.Profiles.FSA.DocumentFiscalYearFocus
            order by $fy descending
            count $i where $i eq 1
            return $filing
    else
        for $a as object in archives:archives-for-entities($entities)
        where empty($filingKind) or $a.Profiles.FSA.FilingKinds[] = $filingKind
        where (empty($fiscalYear) or
               $fiscalYear = 0 or
               $fiscalYear = $a.Profiles.FSA.DocumentFiscalYearFocus)
               and (empty($fiscalPeriod) or ($fiscalPeriod = "ALL") or
               $a.Profiles.FSA.DocumentFiscalPeriodFocus = $fiscalPeriod)
        return $a
};

(:~
 :
Return latest filings of entities and fiscal periods.

 :
 : @param $profile-name the name of the profile (e.g., SEC, Japan, Generic).
 : @param $entities a sequence of entity objects.
 : @param $fiscal-periods a set of fiscal periods such as "Q1", "Q2", "Q3", "Q4", "FY"
 :
 : @return the latest archives for given entities and fiscal periods.
 :)
declare function japan:latest-filings(
    $entities as object*,
    $fiscal-periods as string*) as object*
{
    (
        error(xs:QName("japan:NOT_IMPLEMENTED"),
            "japan profile: Getting latest-filings for entities not implemented."),

        $entities,
        $fiscal-periods
    )
};


Fixed new test.

Fixed new test.


Fixed typo.

Fixed typo.

jsoniq version "1.0";

(:
 : Copyright 2006-2011 The FLWOR Foundation.
 :
 : Licensed under the Apache License, Version 2.0 (the "License");
 : you may not use this file except in compliance with the License.
 : You may obtain a copy of the License at
 :
 : http://www.apache.org/licenses/LICENSE-2.0
 :
 : Unless required by applicable law or agreed to in writing, software
 : distributed under the License is distributed on an "AS IS" BASIS,
 : WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 : See the License for the specific language governing permissions and
 : limitations under the License.
 :)

(:===========================================================================:)

(:~
 : This module provides an API for parsing and serializing CSV (comma-separated
 : values) files.
 : See RFC 4180,
 : "Common Format and MIME Type for Comma-Separated Values (CSV) Files."
 :
 : @author Paul J. Lucas
 : @project Zorba/Data Converters/CSV
 :)

module namespace csv = "http://zorba.io/modules/json-csv";

declare namespace ver = "http://zorba.io/options/versioning";
declare option ver:module-version "1.0";

(:===========================================================================:)

(:~
 : Parses a CSV (comma-separated values) string using the given options.
 : A newline (U+000A), optionally preceeded by a carriage-return (U+000D),
 : terminates lines, aka, "records."
 :

 : Quoted values are always considered strings;
 : unquoted values are attempted to be cast to other types, e.g., integer
 : (unless the cast-unquoted-values option is false).
 : Casting is attempted in the following order:
 : integer, decimal, double, and boolean.
 : If casting fails, the value is considered a string.
 : Header field names are always considered strings even if unquoted.
 :

 : In addition to the "normal" values of
 : true and false for boolean,
 : T and Y are also considered "true"
 : and F and N are also considered "false."
 :
 : @param $csv The CSV string to parse.
 : @param $options The options to use:
 :

 :
cast-unquoted-values

 :

 :        Whether to attempt to cast unquoted values to
 :        integer, decimal, double, or boolean;
 :        default: true.
 :

 :
extra-name

 :

 :        The field name for extra values, if any;
 :        default: none (error csv:EXTRA_VALUE is raised).
 :        If this option is given and a line contains one or more extra values
 :        (that is, values that have no corresponding field names),
 :        then the extra values are assigned as the values
 :        for fields having extra-name as their names.
 :

 :        If extra-name contains a # (U+0023),
 :        then the # is substituted with the field number
 :        (where field numbers start at 1).
 :        If extra-name does not contains a #,
 :        then the field number is appended.
 :

 :
field-names

 :

 :        A JSON array of strings denoting field names;
 :        default: none.
 :        If this option is given, then the first CSV line is assumed not to be
 :        a header line; if omitted, then the first CSV line is assumed to be a
 :        header line and the field names are taken from this line.
 :

 :
missing-value

 :

 :        What should happen when a missing value is detected;
 :        default: "null".
 :        A "missing" value is one of:
 :

 :
Two consecutive separator characters.

 :
A separator character as either the first
 :              or last character on a line.

 :
Fewer values than the number of field names.

 :

 :        When a missing value is detected,
 :        the value of this option determines what happens:
 :

 :
"error"

 :
Error csv:MISSING_VALUE is raised.

 :
"omit"

 :
Both the value and its key are omitted from the result
 :                object.

 :
"null"

 :
The value is set to null.

 :

 :

 :
quote-char

 :

 :        The single ASCII character that may be used to quote values;
 :        default: " (U+0022).
 :

 :
quote-escape

 :

 :        The single ASCII character used to escape quote-char;
 :        default: same as quote-char.
 :        If quote-escape equals quote-char,
 :        it means that quote-char must be doubled to escape it.
 :        If quote-escape does not equal quote-char,
 :        it means that quote-escape is used to escape
 :        quote-char.
 :        For example, a quote-char of " (U+0022)
 :        and a quote-escape of \ (U+005C) means that
 :        quotes will be escaped by \".
 :

 :
separator

 :

 :        The single ASCII character used to separate values;
 :        default: , (U+002C).
 :

 :

 : @return a sequence of zero or more JSON objects where each key is a field
 : name and each value is a parsed value.
 : @error csv:INVALID_OPTION if a value of field-names is not an
 : array or one of the array values is not a string;
 : if the quote-char, quote-escape, or
 : separator option is given and it's not a single ASCII
 : character.
 : @error csv:INVALID_CSV_VALUE if a value of some key is not castable to
 : string.
 : field-names option is not a string.
 : @error csv:MISSING_VALUE if a missing value is detected and the
 : missing-value option is "error".
 : @error csv:EXTRA_VALUE if an extra value is detected and the
 : extra-name option is not set.
 :)
declare function csv:parse( $csv as string, $options as object() )
  as object()* external;

(:~
 : Parses a CSV (comma-separated values) string using the default options.
 : A newline (U+000A), optionally preceeded by a carriage-return (U+000D),
 : terminates lines, aka, "records."
 :

 : Quoted values are always considered strings;
 : unquoted values are attempted to be cast to other types, e.g., integer
 : (unless the cast-unquoted-values option is false).
 : Casting is attempted in the following order:
 : integer, decimal, double, and boolean.
 : If casting fails, the value is considered a string.
 : Header field names are always considered strings even if unquoted.
 :

 : In addition to the "normal" values of
 : true and false for boolean,
 : T and Y are also considered "true"
 : and F and N are also considered "false."
 :

 : The default options are:
 :

 :
cast-unquoted-values

 :

 :        Whether to attempt to cast unquoted values to
 :        integer, decimal, double, or boolean;
 :        default: true.
 :

 :
extra-name

 :

 :        The field name for extra values, if any;
 :        default: none (error csv:EXTRA_VALUE is raised).
 :

 :
field-names

 :

 :        A JSON array of strings denoting field names;
 :        default: none.
 :        The first CSV line is assumed to be a header line
 :        and the field names are taken from this line.
 :

 :
missing-value

 :

 :        What should happen when a missing value is detected;
 :        default: "null".
 :        A "missing" value is one of:
 :

 :
Two consecutive quote-char characters.

 :
A quote-char character as either the first
 :              or last character on a line.

 :
Fewer values than the number of field names.

 :

 :        When a missing value is detected,
 :        the value is set to null.
 :

 :
quote-char

 :

 :        The single ASCII character that may be used to quote values;
 :        default: " (U+0022).
 :

 :
quote-escape

 :

 :        The single ASCII character used to escape quote-char;
 :        default: same as quote-char.
 :        This means that an escaped quote is doubled as "".
 :

 :
separator

 :

 :        The single ASCII character used to separate values;
 :        default: , (U+002C).
 :

 :

 :
 : @param $csv The CSV string to parse.
 : @return a sequence of zero or more JSON objects where each key is a field
 : name and each value is a parsed value.
 : @error csv:EXTRA_VALUE if an extra value is detected.
 :)
declare function csv:parse( $csv as string )
  as object()*
{
  csv:parse( $csv, {} )
};

(:~
 : Serializes a sequence of JSON objects as CSV (comma-separated values) using
 : the given options.
 :
 : @param $obj The sequence of JSON objects to serialize.
 : @param $options The options to use:
 :

 :
field-names

 :

 :        A JSON array of strings denoting field names;
 :        default: none.
 :        If this option is not set,
 :        the field names are taken from the first JSON object
 :        and the order of the fields is implementation dependent.
 :        If this option is set,
 :        the fields are serialized in the order they are in the array.
 :        In either case,
 :        every JSON object must have the same keys as the first object.
 :

 :
serialize-boolean-as

 :

 :        What strings to serialize true and false as;
 :        default: true and false.
 :        This must be a sub-object with the two keys
 :        "true" and "false", e.g.:
 :        { "true" : "Y", "false" : "N" }.
 :

 :
serialize-header

 :

 :        Whether a header line is included;
 :        default: true.
 :        If true,
 :        the first string result is the header line
 :        comprised of all the objects' keys' names;
 :        if false,
 :        the heder line is not returned.
 :

 :
serialize-null-as

 :

 :        What string to serialize JSON null values as;
 :        default: null.
 :

 :
quote-char

 :

 :        The single ASCII character that may be used to quote values;
 :        default: " (U+0022).
 :

 :
quote-escape

 :

 :        The single ASCII character used to escape quote-char;
 :        default: same as quote-char.
 :        If quote-escape equals quote-char,
 :        it means that quote-char must be doubled to escape it.
 :        If quote-escape does not equal quote-char,
 :        it means that quote-escape is used to escape
 :        quote-char.
 :        For example, a quote-char of " (U+0022)
 :        and a quote-escape of \ (U+005C) means that
 :        quotes will be escaped by \".
 :

 :
separator

 :

 :        The single ASCII character used to separate values;
 :        default: , (U+002C).
 :

 :

 : @return a sequence of strings where each string corresponds to a JSON
 : object, aka, "record."
 : @error csv:INVALID_OPTION if a value of field-names is not an
 : array or one of the array values is not a string;
 : if the quote-char, quote-escape, or
 : separator option is given and it's not a single ASCII
 : character.
 :)
declare function csv:serialize( $obj as object()*, $options as object() )
  as string* external;

(:~
 : Serializes a sequence of JSON objects as CSV (comma-separated values) using
 : the default options.
 : The default options are:
 :

 :
field-names

 :

 :        A JSON array of strings denoting field names;
 :        default: none.
 :        The field names are taken from the first JSON object
 :        and the order of the fields is implementation dependent.
 :

 :
serialize-boolean-as

 :

 :        What strings to serialize true and false as;
 :        default: true and false.
 :

 :
serialize-header

 :

 :        Whether a header line is included;
 :        default: true.
 :        The first string result is the header line
 :        comprised of all the objects' keys' names.
 :

 :
serialize-null-as

 :

 :        What string to serialize JSON null values as;
 :        default: null.
 :

 :
quote-char

 :

 :        The single ASCII character that may be used to quote values;
 :        default: " (U+0022).
 :

 :
quote-escape

 :

 :        The single ASCII character used to escape quote-char;
 :        default: same as quote-char.
 :        This means that quote-char is doubled to escape it.
 :

 :
separator

 :

 :        The single ASCII character used to separate values;
 :        default: , (U+002C).
 :

 :

 :
 : @param $obj The sequence of JSON objects to serialize.
 : @return a sequence of strings where each string corresponds to a JSON
 : object, aka, "record."
 :)
declare function csv:serialize( $obj as object()* )
  as string*
{
  csv:serialize( $obj, {} )
};

(:===========================================================================:)

(: vim:set syntax=xquery et sw=2 ts=2: :)

jsoniq version "1.0";

(:
 : Copyright 2006-2011 The FLWOR Foundation.
 :
 : Licensed under the Apache License, Version 2.0 (the "License");
 : you may not use this file except in compliance with the License.
 : You may obtain a copy of the License at
 :
 : http://www.apache.org/licenses/LICENSE-2.0
 :
 : Unless required by applicable law or agreed to in writing, software
 : distributed under the License is distributed on an "AS IS" BASIS,
 : WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 : See the License for the specific language governing permissions and
 : limitations under the License.
 :)

(:===========================================================================:)

(:~
 : This module provides an API for parsing and serializing CSV (comma-separated
 : values) files.
 : See RFC 4180,
 : "Common Format and MIME Type for Comma-Separated Values (CSV) Files."
 :
 : @author Paul J. Lucas
 : @project Zorba/Data Converters/CSV
 :)

module namespace csv = "http://zorba.io/modules/json-csv";

declare namespace ver = "http://zorba.io/options/versioning";
declare option ver:module-version "1.0";

(:===========================================================================:)

(:~
 : Parses a CSV (comma-separated values) string using the given options.
 : A newline (U+000A), optionally preceeded by a carriage-return (U+000D),
 : terminates lines, aka, "records."
 :

 : Quoted values are always considered strings;
 : unquoted values are attempted to be cast to other types, e.g., integer
 : (unless the cast-unquoted-values option is false).
 : Casting is attempted in the following order:
 : integer, decimal, double, and boolean.
 : If casting fails, the value is considered a string.
 : Header field names are always considered strings even if unquoted.
 :

 : In addition to the "normal" values of
 : true and false for boolean,
 : T and Y are also considered "true"
 : and F and N are also considered "false."
 :
 : @param $csv The CSV string to parse.
 : @param $options The options to use:
 :

 :
cast-unquoted-values

 :

 :        Whether to attempt to cast unquoted values to
 :        integer, decimal, double, or boolean;
 :        default: true.
 :

 :
extra-name

 :

 :        The field name for extra values, if any;
 :        default: none (error csv:EXTRA_VALUE is raised).
 :        If this option is given and a line contains one or more extra values
 :        (that is, values that have no corresponding field names),
 :        then the extra values are assigned as the values
 :        for fields having extra-name as their names.
 :

 :        If extra-name contains a # (U+0023),
 :        then the # is substituted with the field number
 :        (where field numbers start at 1).
 :        If extra-name does not contains a #,
 :        then the field number is appended.
 :

 :
field-names

 :

 :        A JSON array of strings denoting field names;
 :        default: none.
 :        If this option is given, then the first CSV line is assumed not to be
 :        a header line; if omitted, then the first CSV line is assumed to be a
 :        header line and the field names are taken from this line.
 :

 :
missing-value

 :

 :        What should happen when a missing value is detected;
 :        default: "null".
 :        A "missing" value is one of:
 :

 :
Two consecutive separator characters.

 :
A separator character as either the first
 :              or last character on a line.

 :
Fewer values than the number of field names.

 :

 :        When a missing value is detected,
 :        the value of this option determines what happens:
 :

 :
"error"

 :
Error csv:MISSING_VALUE is raised.

 :
"omit"

 :
Both the value and its key are omitted from the result
 :                object.

 :
"null"

 :
The value is set to null.

 :

 :

 :
quote-char

 :

 :        The single ASCII character that may be used to quote values;
 :        default: " (U+0022).
 :

 :
quote-escape

 :

 :        The single ASCII character used to escape quote-char;
 :        default: same as quote-char.
 :        If quote-escape equals quote-char,
 :        it means that quote-char must be doubled to escape it.
 :        If quote-escape does not equal quote-char,
 :        it means that quote-escape is used to escape
 :        quote-char.
 :        For example, a quote-char of " (U+0022)
 :        and a quote-escape of \ (U+005C) means that
 :        quotes will be escaped by \".
 :

 :
separator

 :

 :        The single ASCII character used to separate values;
 :        default: , (U+002C).
 :

 :

 : @return a sequence of zero or more JSON objects where each key is a field
 : name and each value is a parsed value.
 : @error csv:INVALID_OPTION if a value of field-names is not an
 : array or one of the array values is not a string;
 : if the quote-char, quote-escape, or
 : separator option is given and it's not a single ASCII
 : character.
 : @error csv:INVALID_CSV_VALUE if a value of some key is not castable to
 : string.
 : field-names option is not a string.
 : @error csv:MISSING_VALUE if a missing value is detected and the
 : missing-value option is "error".
 : @error csv:EXTRA_VALUE if an extra value is detected and the
 : extra-name option is not set.
 :)
declare function csv:parse( $csv as string, $options as object() )
  as object()* external;

(:~
 : Parses a CSV (comma-separated values) string using the default options.
 : A newline (U+000A), optionally preceeded by a carriage-return (U+000D),
 : terminates lines, aka, "records."
 :

 : Quoted values are always considered strings;
 : unquoted values are attempted to be cast to other types, e.g., integer
 : (unless the cast-unquoted-values option is false).
 : Casting is attempted in the following order:
 : integer, decimal, double, and boolean.
 : If casting fails, the value is considered a string.
 : Header field names are always considered strings even if unquoted.
 :

 : In addition to the "normal" values of
 : true and false for boolean,
 : T and Y are also considered "true"
 : and F and N are also considered "false."
 :

 : The default options are:
 :

 :
cast-unquoted-values

 :

 :        Whether to attempt to cast unquoted values to
 :        integer, decimal, double, or boolean;
 :        default: true.
 :

 :
extra-name

 :

 :        The field name for extra values, if any;
 :        default: none (error csv:EXTRA_VALUE is raised).
 :

 :
field-names

 :

 :        A JSON array of strings denoting field names;
 :        default: none.
 :        The first CSV line is assumed to be a header line
 :        and the field names are taken from this line.
 :

 :
missing-value

 :

 :        What should happen when a missing value is detected;
 :        default: "null".
 :        A "missing" value is one of:
 :

 :
Two consecutive quote-char characters.

 :
A quote-char character as either the first
 :              or last character on a line.

 :
Fewer values than the number of field names.

 :

 :        When a missing value is detected,
 :        the value is set to null.
 :

 :
quote-char

 :

 :        The single ASCII character that may be used to quote values;
 :        default: " (U+0022).
 :

 :
quote-escape

 :

 :        The single ASCII character used to escape quote-char;
 :        default: same as quote-char.
 :        This means that an escaped quote is doubled as "".
 :

 :
separator

 :

 :        The single ASCII character used to separate values;
 :        default: , (U+002C).
 :

 :

 :
 : @param $csv The CSV string to parse.
 : @return a sequence of zero or more JSON objects where each key is a field
 : name and each value is a parsed value.
 : @error csv:EXTRA_VALUE if an extra value is detected.
 :)
declare function csv:parse( $csv as string )
  as object()*
{
  csv:parse( $csv, {} )
};

(:~
 : Serializes a sequence of JSON objects as CSV (comma-separated values) using
 : the given options.
 :
 : @param $obj The sequence of JSON objects to serialize.
 : @param $options The options to use:
 :

 :
field-names

 :

 :        A JSON array of strings denoting field names;
 :        default: none.
 :        If this option is not set,
 :        the field names are taken from the first JSON object
 :        and the order of the fields is implementation dependent.
 :        If this option is set,
 :        the fields are serielized in the order they are in the array.
 :        In either case,
 :        every JSON object must have the same keys as the first object.
 :

 :
serialize-boolean-as

 :

 :        What strings to serialize true and false as;
 :        default: true and false.
 :        This must be a sub-object with the two keys
 :        "true" and "false", e.g.:
 :        { "true" : "Y", "false" : "N" }.
 :

 :
serialize-header

 :

 :        Whether a header line is included;
 :        default: true.
 :        If true,
 :        the first string result is the header line
 :        comprised of all the objects' keys' names;
 :        if false,
 :        the heder line is not returned.
 :

 :
serialize-null-as

 :

 :        What string to serialize JSON null values as;
 :        default: null.
 :

 :
quote-char

 :

 :        The single ASCII character that may be used to quote values;
 :        default: " (U+0022).
 :

 :
quote-escape

 :

 :        The single ASCII character used to escape quote-char;
 :        default: same as quote-char.
 :        If quote-escape equals quote-char,
 :        it means that quote-char must be doubled to escape it.
 :        If quote-escape does not equal quote-char,
 :        it means that quote-escape is used to escape
 :        quote-char.
 :        For example, a quote-char of " (U+0022)
 :        and a quote-escape of \ (U+005C) means that
 :        quotes will be escaped by \".
 :

 :
separator

 :

 :        The single ASCII character used to separate values;
 :        default: , (U+002C).
 :

 :

 : @return a sequence of strings where each string corresponds to a JSON
 : object, aka, "record."
 : @error csv:INVALID_OPTION if a value of field-names is not an
 : array or one of the array values is not a string;
 : if the quote-char, quote-escape, or
 : separator option is given and it's not a single ASCII
 : character.
 :)
declare function csv:serialize( $obj as object()*, $options as object() )
  as string* external;

(:~
 : Serializes a sequence of JSON objects as CSV (comma-separated values) using
 : the default options.
 : The default options are:
 :

 :
field-names

 :

 :        A JSON array of strings denoting field names;
 :        default: none.
 :        The field names are taken from the first JSON object
 :        and the order of the fields is implementation dependent.
 :

 :
serialize-boolean-as

 :

 :        What strings to serialize true and false as;
 :        default: true and false.
 :

 :
serialize-header

 :

 :        Whether a header line is included;
 :        default: true.
 :        The first string result is the header line
 :        comprised of all the objects' keys' names.
 :

 :
serialize-null-as

 :

 :        What string to serialize JSON null values as;
 :        default: null.
 :

 :
quote-char

 :

 :        The single ASCII character that may be used to quote values;
 :        default: " (U+0022).
 :

 :
quote-escape

 :

 :        The single ASCII character used to escape quote-char;
 :        default: same as quote-char.
 :        This means that quote-char is doubled to escape it.
 :

 :
separator

 :

 :        The single ASCII character used to separate values;
 :        default: , (U+002C).
 :

 :

 :
 : @param $obj The sequence of JSON objects to serialize.
 : @return a sequence of strings where each string corresponds to a JSON
 : object, aka, "record."
 :)
declare function csv:serialize( $obj as object()* )
  as string*
{
  csv:serialize( $obj, {} )
};

(:===========================================================================:)

(: vim:set syntax=xquery et sw=2 ts=2: :)


:green_heart: remove unused parameter

:green_heart: remove unused parameter

jsoniq version "1.0";
module namespace mw = "http://28.io/modules/xbrl/mongo-wrapper";

import module namespace mw-sec = "http://28.io/modules/xbrl/profiles/sec/mongo-wrapper";
import module namespace mw-japan = "http://28.io/modules/xbrl/profiles/japan/mongo-wrapper";
import module namespace config = "http://apps.28.io/config";
import module namespace mongo = "http://www.28msec.com/modules/mongodb";
import module namespace credentials = "http://www.28msec.com/modules/credentials";

declare %an:strictlydeterministic function mw:connection() as anyURI
{
  let $credentials :=
      let $credentials := credentials:credentials("MongoDB", "xbrl")
      return if (empty($credentials))
             then error(QName("mw:CONNECTION-FAILED"), "no xbrl MongoDB configured")
             else $credentials
  return
    try {
      mongo:connect($credentials)
    } catch mongo:* {
      error(QName("mw:CONNECTION-FAILED"), $err:description)
    }
};

declare %private function mw:check-result(
    $results as object()*,
    $collection as string) as object()*
{
    if(empty($results."$err"))
    then $results
    else error(QName("mw:INVALID-PARAMETER"),
               string-join((
                 $results."$err",
                 "COLLECTION: " || $collection
               ), " "))
};

declare function mw:find($collection as string, $query as object) as object()*
{
  let $conn := mw:connection()
  let $hint as object := mw:hint($collection, $query)
  return
    mw:check-result(
        mongo:find($conn, $collection, $hint),
        $collection)
};

declare function mw:find($collection as string, $query as object, $projection as object) as object()*
{
  let $conn := mw:connection()
  let $hint as object := mw:hint($collection, $query)
  return
    mw:check-result(
      mongo:find($conn, $collection, $hint, $projection, {}),
      $collection)
};

declare function mw:run-cmd-deterministic($command as object) as object*
{
  let $conn := mw:connection()
  return mongo:run-cmd-deterministic($conn, $command)
};

declare %private function mw:hint($collection as string, $query as object) as object
{
  switch(lower-case($config:profile-name))
    case "sec"
      return mw-sec:hint($collection, $query)
    case "japan"
      return mw-japan:hint($collection, $query)
    default
      return $query
};

(:
  Heuristics detection of whether a condition in the query is selective and should be
  used to decide the index to use
:)
declare %private function mw:is-selective($query as object, $field as string) as boolean
{
    exists($query($field)) and
      (
        not($query($field) instance of object) or (: Equality checks are of type atomic - not object - other kinds are disallowed :)
        exists($query($field)("$in")) (: $in operator :)
      )
};

jsoniq version "1.0";
module namespace mw = "http://28.io/modules/xbrl/mongo-wrapper";

import module namespace mw-sec = "http://28.io/modules/xbrl/profiles/sec/mongo-wrapper";
import module namespace mw-japan = "http://28.io/modules/xbrl/profiles/japan/mongo-wrapper";
import module namespace config = "http://apps.28.io/config";
import module namespace mongo = "http://www.28msec.com/modules/mongodb";
import module namespace credentials = "http://www.28msec.com/modules/credentials";

declare %an:strictlydeterministic function mw:connection() as anyURI
{
  let $credentials :=
      let $credentials := credentials:credentials("MongoDB", "xbrl")
      return if (empty($credentials))
             then error(QName("mw:CONNECTION-FAILED"), "no xbrl MongoDB configured")
             else $credentials
  return
    try {
      mongo:connect($credentials)
    } catch mongo:* {
      error(QName("mw:CONNECTION-FAILED"), $err:description)
    }
};

declare %private function mw:check-result(
    $results as object()*,
    $collection as string,
    $hint as object) as object()*
{
    if(empty($results."$err"))
    then $results
    else error(QName("mw:INVALID-PARAMETER"),
               string-join((
                 $results."$err",
                 "COLLECTION: " || $collection
               ), " "))
};

declare function mw:find($collection as string, $query as object) as object()*
{
  let $conn := mw:connection()
  let $hint as object := mw:hint($collection, $query)
  return
    mw:check-result(
        mongo:find($conn, $collection, $hint),
        $collection,
        $hint)
};

declare function mw:find($collection as string, $query as object, $projection as object) as object()*
{
  let $conn := mw:connection()
  let $hint as object := mw:hint($collection, $query)
  return
    mw:check-result(
      mongo:find($conn, $collection, $hint, $projection, {}),
      $collection,
      $hint)
};

declare function mw:run-cmd-deterministic($command as object) as object*
{
  let $conn := mw:connection()
  return mongo:run-cmd-deterministic($conn, $command)
};

declare %private function mw:hint($collection as string, $query as object) as object
{
  switch(lower-case($config:profile-name))
    case "sec"
      return mw-sec:hint($collection, $query)
    case "japan"
      return mw-japan:hint($collection, $query)
    default
      return $query
};

(:
  Heuristics detection of whether a condition in the query is selective and should be
  used to decide the index to use
:)
declare %private function mw:is-selective($query as object, $field as string) as boolean
{
    exists($query($field)) and
      (
        not($query($field) instance of object) or (: Equality checks are of type atomic - not object - other kinds are disallowed :)
        exists($query($field)("$in")) (: $in operator :)
      )
};


Update resolution.jq

Update resolution.jq

jsoniq version "1.0";

module namespace resolution = "http://28.io/modules/xbrl/resolution";

import module namespace components = "http://28.io/modules/xbrl/components";
import module namespace concepts = "http://28.io/modules/xbrl/concepts";
import module namespace facts = "http://28.io/modules/xbrl/facts";
import module namespace hypercubes = "http://28.io/modules/xbrl/hypercubes";
import module namespace networks = "http://28.io/modules/xbrl/networks";

(: TODOs
- Options for relationship networks (formulaAxis, depth)
:)

(:~
 : Converts a definition breakdown to a structural breakdown
 :
 : @param $breakdown a breandowk
 : @param $components a sequence of components
 : @param $parent-child-order "parentFirst" or "childrenFirst"
 : @param $concepts the concept objects (for inferring the labels)
 : @param $options the option object
 :
 : @error resolution:UNKNOWN-DEFINITION-NODE-KIND if a definition node kind
 : is unrecognized.
 : @error resolution:UNRESOLVED-CONCEPT-RELATIONSHIP if a root concept
 : cannot be resolved.
 : @error resolution:UNRESOLVED-DIMENSION-RELATIONSHIP if a root member
 : cannot be resolved.
 : @error resolution:NON-ABSTRACT-MERGE-NODE if a rule node is merge,
 : but non-abstract.
 :
 : @return the converted, structural breakdown.
 :)
declare %private function resolution:convert-breakdown(
    $breakdown as object,
    $components as object*,
    $parent-child-order as string?,
    $concepts as object*,
    $options as object?) as object
{
    let $parent-child-order as string? := ($breakdown.ParentChildOrder, $parent-child-order)[1]

    let $labels as array := $breakdown.BreakdownLabels

    let $unbalanced-trees as object* := resolution:convert-definition-nodes(
        $breakdown.BreakdownTrees[],
        $components,
        $parent-child-order,
        $concepts,
        $options
    )
    let $balanced-trees as object* := resolution:height-balance($unbalanced-trees)

    return {
        BreakdownLabels: $labels,
        BreakdownTrees: [ $balanced-trees ]
    }
};

(:~
 : Converts each definition node to one or more structural nodes
 :
 : @param $definition-nodes some definition nodes.
 : @param $components a sequence of components
 : @param $parent-child-order "parentFirst" or "childrenFirst"
 : @param $concepts the concept objects (for inferring the labels)
 : @param $options the options object
 :
 : @error resolution:UNKNOWN-DEFINITION-NODE-KIND if a definition node kind
 : is unrecognized.
 : @error resolution:UNRESOLVED-CONCEPT-RELATIONSHIP if a root concept
 : cannot be resolved.
 : @error resolution:UNRESOLVED-DIMENSION-RELATIONSHIP if a root member
 : cannot be resolved.
 : @error resolution:NON-ABSTRACT-MERGE-NODE if a rule node is merge,
 : but non-abstract.
 :
 : @return the converted structural nodes.
 :)
declare %private function resolution:convert-definition-nodes(
    $definition-nodes as object*,
    $components as object*,
    $parent-child-order as string?,
    $concepts as object*,
    $options as object?) as object*
{
    for $definition-node as object in $definition-nodes
    let $parent-child-order as string? := ($definition-node.ParentChildOrder, $parent-child-order)[1]
    for $converted-node in
      switch($definition-node.Kind)
      case "Rule" return resolution:convert-rule-node(
          $definition-node,
          $components,
          $parent-child-order,
          $concepts,
          $options)
      case "Aspect" return resolution:convert-aspect-node(
          $definition-node,
          $components,
          $parent-child-order,
          $concepts,
          $options)
      case "ConceptRelationship" return resolution:convert-concept-relationship-node(
          $definition-node,
          $components,
          $parent-child-order,
          $concepts,
          $options)
      case "DimensionRelationship" return resolution:convert-dimension-relationship-node(
          $definition-node,
          $components,
          $parent-child-order,
          $concepts)
      default return error(
          QName("resolution:UNKNOWN-DEFINITION-NODE-KIND"),
          "Unknown definition node kind: $definition-node.Kind")
    return if(exists($definition-node.Id))
           then copy $c := $converted-node
                modify for $node in ($c, descendant-objects($c).Children[])
                       return insert json { Id: $definition-node.Id } into $node
                return $c
           else $converted-node
};

(:~
 : Retrieves the labels from the components' cache (default language)
 : or from the remove collection cache.
 :
 : @param $concept-names a sequence of concept names.
 : @param $components a sequence of components
 : @param $concepts the concept objects (for inferring the labels)
 : @param $label-role the desired label role
 : @param $options the options object
 :
 : @return the labels
 :)
declare %private function resolution:labels(
    $concept-names as string*,
    $components as object*,
    $concepts as object*,
    $label-role as string,
    $options as object?) as string*
{
    let $components-with-the-language-as-default :=
        $components[not $$.$components:DEFAULT-LANGUAGE ne $options.Language]

    let $labels-from-local-metadata as string* :=
        let $default-hypercubes as object* :=
            hypercubes:hypercubes-for-components($components-with-the-language-as-default, "xbrl:DefaultHypercube")
        for $local-metadata as object in
            descendant-objects($default-hypercubes.Aspects)
        let $local-metadata-name := $local-metadata.Name
        let $local-metadata-preferred-label-role as string := ($local-metadata.PreferredLabelRole, $concepts:STANDARD_LABEL_ROLE)[1]
        where $local-metadata-name = $concept-names and
              $local-metadata-preferred-label-role eq $label-role
        return
            $local-metadata.Label

    let $labels-from-concepts-collection as string* :=
        if(empty($labels-from-local-metadata))
        then
            concepts:labels-for-components(
                $concept-names,
                $components,
                $label-role,
                ($options.Language, "en-US")[1],
                $concepts,
                ())
        else ()

    return ($labels-from-local-metadata, $labels-from-concepts-collection)
 };

(:~
 : Converts a rule definition node to one or more structural nodes.
 : A rule node restricts a dimension to a value.
 :
 : @param $definition-node a definition node.
 : @param $components a sequence of components
 : @param $parent-child-order "parentFirst" or "childrenFirst"
 : @param $concepts the concept objects (for inferring the labels)
 : @param $options the options object
 :
 : @error resolution:NON-ABSTRACT-MERGE-NODE if a rule node is merge,
 : but non-abstract.
 :
 : @return the converted structural nodes.
 :)
declare %private function resolution:convert-rule-node(
    $definition-node as object,
    $components as object*,
    $parent-child-order as string?,
    $concepts as object*,
    $options as object?) as object*
{
    let $main-members := values(values($definition-node.AspectRulesSet))

    let $labels := (
        $definition-node.Labels[],
        resolution:labels(
            $main-members,
            $components,
            $concepts,
            $concepts:STANDARD_LABEL_ROLE,
            $options)
    )

    let $children := resolution:convert-definition-nodes(
        $definition-node.Children[],
        $components,
        $parent-child-order,
        $concepts,
        $options)
    let $roll-up := {
        Labels: [ ],
        ConstraintSets : {
            "": { }

        },
        RollUp: true
    }
    let $constraint-sets := {|
        for $tag in keys($definition-node.AspectRulesSet)
        return {
            $tag: {|
                for $aspect in keys($definition-node.AspectRulesSet.$tag)
                return {
                    $aspect: $definition-node.AspectRulesSet.$tag.$aspect
                }
            |}
        }
    |}
    let $merged-children :=
        for $child in $children
        return copy $c := $child
        modify for $tag in keys($c.ConstraintSets)
               return replace value of json $c.ConstraintSets.$tag with facts:merge-objects(
                    $c.ConstraintSets.$tag,
                    $constraint-sets.$tag,
                    true)
        return $c
    return switch(true)
           case not $definition-node.Abstract and $definition-node.Merge
                return error(QName("resolution:NON-ABSTRACT-MERGE-NODE"), "A definition rule node cannot be non-abstract and merged.")
           case $definition-node.Merge return $merged-children
           case $definition-node.Abstract return {|
                {
                    Labels: [  $labels ],
                    ConstraintSets: $constraint-sets
                },
                if(exists($definition-node.TagSelectors))
                then {
                    TagSelectors: $definition-node.TagSelectors
                }
                else (),
                if(exists($children)) then {
                    Children: [ $children ]
                }
                else ()
           |}
            default return {|
                {
                    Labels: [  $labels ],
                    ConstraintSets: $constraint-sets
                },
                if(exists($definition-node.TagSelectors))
                then {
                    TagSelectors: $definition-node.TagSelectors
                }
                else (),
                if(exists($children))
                then {
                    Children: switch(true)
                              case $parent-child-order eq "parentFirst" return [$roll-up, $children]
                              default return [$children, $roll-up]
                }
                else (),
                if($definition-node.IsTotal)
                then { IsTotal: true }
                else ()
            |}
};

(:~
 : Convert an aspect definition node to one or more structural nodes.
 : An aspect nodes will expand to all values found in the fact pool during
 : the layouting stage.
 :
 : @param $definition-node a definition node.
 : @param $components a sequence of components
 : @param $parent-child-order "parentFirst" or "childrenFirst"
 : @param $concepts the concept objects (for inferring the labels)
 : @param $options the options object
 :
 : @return the converted structural node.
 :)
declare %private function resolution:convert-aspect-node(
    $definition-node as object,
    $components as object*,
    $parent-child-order as string?,
    $concepts as object*,
    $options as object?) as object
{
    let $children :=  resolution:convert-definition-nodes(
        $definition-node.Children[],
        $components,
        $parent-child-order,
        $concepts,
        $options)
    let $constrained-aspect := $definition-node.Aspect
    return {|
        {
            Open: true,
            Aspect: $constrained-aspect
        },
        if ($children)
        then { Children: [ $children ] }
        else ()
    |}
};

(:~
 : Convert a concept relationship definition node to one or more structural nodes.
 : A concept relationship node will automatically expand a network to a hierarchy
 : of structural nodes.
 :
 : @param $definition-node a definition node.
 : @param $components a sequence of components
 : @param $parent-child-order "parentFirst" or "childrenFirst"
 : @param $concepts the concept objects (for inferring the labels)
 :
 : @error resolution:UNRESOLVED-CONCEPT-RELATIONSHIP if the root concept
 : cannot be resolved.
 :
 : @return the converted structural node.
 :)
declare %private function resolution:convert-concept-relationship-node(
    $definition-node as object,
    $components as object*,
    $parent-child-order as string?,
    $concepts as object*,
    $options as object?) as object
{
    let $link-role := $definition-node.LinkRole
    let $link-name := $definition-node.LinkName
    let $arc-role := $definition-node.ArcRole
    let $arc-name := $definition-node.ArcName
    let $root := $definition-node.RelationshipSource
    let $network as object? := networks:networks-for-components($components)[
        $$.LinkRole eq $link-role and
        $$.LinkName eq $link-name and
        $$.ArcRole eq $arc-role and
        $$.ArcName eq $arc-name
    ]
    let $subnetwork := descendant-objects($network.Trees)[$$.Name eq $root]
    return if(exists($subnetwork))
    then resolution:expand-concept-network($subnetwork, $components, $parent-child-order, $concepts, $options)
    else error(QName("resolution:UNRESOLVED-CONCEPT-RELATIONSHIP"), $root || ": The concept root could not be resolved.")
};

(:~
 : Helper, recursive function for resolution:convert-concept-relationship-node#3
 :
 : @param $network a network to expand.
 : @param $components a sequence of components.
 : @param $parent-child-order "parentFirst" or "childrenFirst"
 : @param $concepts the concept objects (for inferring the labels)
 :
 : @return the converted structural nodes.
 :)
declare %private function resolution:expand-concept-network(
    $network as object,
    $components as object*,
    $parent-child-order as string?,
    $concepts as object*,
    $options as object?) as object*
{
    let $concept := $network.Name
    let $default-hypercube := hypercubes:hypercubes-for-components($components, "xbrl:DefaultHypercube")
    let $concept-metadata := $default-hypercube.Aspects."xbrl:Concept".Domains."xbrl:ConceptDomain".Members.$concept[1]
    let $label :=
        if(not $options.Language != $components.$components:DEFAULT-LANGUAGE)
        then $network.Label
        else
        resolution:labels(
            $concept,
            $components,
            $concepts,
            ($network.PreferredLabelRole, $concepts:STANDARD_LABEL_ROLE)[1],
            $options)
    return
    {|
        {
            Labels: [ $label ],
            ConstraintSets: {
                "" : { "xbrl:Concept" : $concept }
            }
        },

        switch($network.PreferredLabelRole)
        case "http://www.xbrl.org/2003/role/totalLabel"
        return {
            IsTotal: true
        }
        case "http://www.xbrl.org/2009/role/negatedLabel"
        return {
            IsNegated: true
        }
        case "http://www.xbrl.org/2009/role/negatedTerseLabel"
        return {
            IsNegated: true
        }
        case "http://www.xbrl.org/2003/role/periodStartLabel"
        return {
            TagSelectors: [ "table.periodStart" ]
        }
        case "http://www.xbrl.org/2003/role/periodEndLabel"
        return {
            TagSelectors: [ "table.periodEnd" ],
            IsTotal: true
        }
        default return (),

        let $sub-networks := (values($network.To), $network.To[])
        let $converted-subnetworks :=
            for $sub-network in $sub-networks
            let $order := $sub-network.Order
            order by $order
            return
                resolution:expand-concept-network(
                        $sub-network,
                        $components,
                        $parent-child-order,
                        $concepts,
                        $options
                    )
        let $roll-up :=
            if($concept-metadata.IsAbstract)
            then ()
            else {
                Labels: [],
                RollUp: true
            }
        where exists($converted-subnetworks)
        return {
            Children: [
                switch($parent-child-order)
                case "parentFirst" return ($roll-up, $converted-subnetworks)
                default return ($converted-subnetworks, $roll-up)
            ]
        }

    |}
};

(:~
 : Convert a dimension relationship definition node to one or more structural nodes.
 : A dimension relationship node will automatically expand a network to a hierarchy
 : of structural nodes.
 : @param $definition-node a definition node.
 : @param $components a sequence of components
 : @param $parent-child-order "parentFirst" or "childrenFirst"
 : @param $concepts the concept objects (for inferring the labels)
 :
 : @error resolution:UNRESOLVED-CONCEPT-RELATIONSHIP if the root member
 : cannot be resolved.
 :
 : @return the converted structural node.
 :)
declare %private function resolution:convert-dimension-relationship-node(
    $definition-node as object,
    $components as object*,
    $parent-child-order as string?,
    $concepts as object*) as object
{
    let $link-role := $definition-node.LinkRole
    let $dimension := $definition-node.Dimension
    let $root := $definition-node.RelationshipSource
    let $hypercubes as object* := hypercubes:hypercubes-for-components($components[$$.Role eq $link-role])
    let $subnetwork as object := descendant-objects($hypercubes.Aspects.$dimension)[$$.Name eq $root][1]
    return if(exists($subnetwork))
    then resolution:expand-dimension-network($dimension, $subnetwork, $components, $parent-child-order, $concepts)
    else error(QName("resolution:UNRESOLVED-DIMENSION-RELATIONSHIP"), $root || ": The dimension member root could not be resolved.")
};

(:
    Helper, recursive function for resolution:convert-dimension-relationship-node#3
:)
declare function resolution:expand-dimension-network(
    $dimension as string,
    $network as object,
    $components as object*,
    $parent-child-order as string?,
    $concepts as object*) as object
{
    let $value := $network.Name
    let $label :=
          if(not $options.Language != $components.$components:DEFAULT-LANGUAGE)
          then $network.Label
          else
          resolution:labels(
            $value,
            $components,
            $concepts,
            ($network.PreferredLabelRole, $concepts:STANDARD_LABEL_ROLE)[1],
            $options
    return
    {|
        {
            Labels: [ $label],
            ConstraintSets: {
                "" : { $dimension : $value }
            }
        },
        let $sub-networks := values($network.Members)
        let $converted-subnetworks :=
            for $sub-network in $sub-networks
            return resolution:expand-dimension-network(
                        $dimension,
                        $sub-network,
                        $components,
                        $parent-child-order,
                        $concepts
                )
        let $roll-up :={
            Labels: [],
            RollUp: true
        }
        where exists($converted-subnetworks)
        return { Children: [ $converted-subnetworks, $roll-up ] }
    |}
};

(:
    Helper function that returns the depth of breakdown trees set.
:)
declare function resolution:depth($axis-breakdown-trees as object*) as integer
{
    switch(true)
    case empty($axis-breakdown-trees) return 0
    case empty($axis-breakdown-trees.Children[]) return 1
    default return max($axis-breakdown-trees.Children[] ! (1 + resolution:depth($$)))
};

(:~
 : Helper function that height-balances a breakdown trees set,
 : by adding roll-up nodes to get a uniform depth.
 :
 : @param $axis-breakdown-trees the breakdown trees for an axis
 :
 : @return the balanced breakdown trees.
 :)
declare function resolution:height-balance($axis-breakdown-trees as object*) as object*
{
    let $depth := resolution:depth($axis-breakdown-trees)
    return resolution:height-balance($axis-breakdown-trees, $depth)
};

(:~
 : Helper, recursive function for resolution:height-balance#1.
 :
 : @param $axis-breakdown-trees the breakdown trees for an axis
 : @parem the depth at which these trees should get balanced.
 :
 : @return the balanced breakdown trees.
 :)
declare function resolution:height-balance($axis-breakdown-trees as object*, $desired-depth as integer) as object*
{
  let $roll-up-cell := {
    CellLabels: [],
    ConstraintSets: {"" : {}},
    RollUp: true
  }
  return
    for $tree in $axis-breakdown-trees
    return switch(true)
           case $desired-depth gt 1 and empty($tree.Children)
           return copy $t := $tree
                  modify insert json {
                    Children: [
                      resolution:height-balance($roll-up-cell, $desired-depth - 1)
                    ]
                  } into $t
                  return $t
                case $desired-depth gt 1 and exists($tree.Children)
                  return copy $t := $tree
                         modify replace value of json $t.Children with [
                           $t.Children[] ! resolution:height-balance($$, $desired-depth - 1)
                         ]
                         return $t
                case $desired-depth eq 1 and empty($tree.Children)
                  return $tree
                default
                  return error(QName("resolution:UNFORESEEN-ERROR"), "An error occurred while height-balancing")
};

(:~
 : Retrieves the metadata for some members from a component.
 :
 : @param $components a sequence of components.
 : @param $member-names the names of the members for which to retrieve the metadata.
 :
 : @return the metadata for the supplied members.
 :)
declare %private function resolution:metadata(
    $components as object*,
    $member-names as string*) as object*
{
    let $default-hypercube := hypercubes:hypercubes-for-components($components, "xbrl:DefaultHypercube")
    return descendant-objects($default-hypercube.Aspects)[$$.Name = $member-names][1]
};

(:~
  Resolves a definition model to a structural model, given a component.

  @param $definition-model A definition mode, in 28msec's proprietary JSON format.
  @param $component A component, in 28msec's proprietary JSON format.

  @error resolution:UNFORESEEN-ERROR Something went wrong, contact us.
  @error resolution:UNKNOWN-DEFINITION-NODE-KIND A definition node was not recognized.

  @return a structural model
:)
declare function resolution:resolve(
    $definition-model as object,
    $components as object*) as object
{
    resolution:resolve($definition-model, $components, ())
};

(:~
 : Resolves a definition model to a structural model, given a component.
 :
 : @param $definition-model A definition mode, in 28msec's proprietary JSON format.
 : @param $component A component, in 28msec's proprietary JSON format.
 : @param $options Optional parameters among which
 : <ul>
 :   <li>Hypercube: override the components' hypercubes with the provided hypercube
 :      (this will only affect the default values used later in the layout pipeline).</li>
 :    <li>Language: override the components' default language in the rendering.</li>
 : </ul>
 :
 : @error resolution:UNFORESEEN-ERROR Something went wrong, contact us.
 : @error resolution:UNKNOWN-DEFINITION-NODE-KIND A definition node was not recognized.
 : @error resolution:UNRESOLVED-CONCEPT-RELATIONSHIP if the root concept
 : cannot be resolved.
 : @error resolution:UNRESOLVED-DIMENSION-RELATIONSHIP if the root member
 : cannot be resolved.
 : @error resolution:NON-ABSTRACT-MERGE-NODE if a rule node is merge,
 : but non-abstract.
 :
 : @return a structural model
 :)
declare function resolution:resolve(
    $definition-model as object,
    $components as object*,
    $options as object?) as object
{
    let $concepts as object* := concepts:concepts-for-components(
        $concepts:ALL_CONCEPT_NAMES,
        $components)
    let $hypercubes as object* :=
        if(exists($options.Hypercube))
        then $options.Hypercube
        else values($components.Hypercubes)
    return {
        ModelKind: "StructuralModel",
        TableSetLabels: $definition-model.Labels,
        Component: {
            Role: $components.Role[1],
            Label: $components.Label[1]
        },
        TableSet : [
            {
                Breakdowns: {|
                    for $axis in keys($definition-model.Breakdowns)
                    return {
                        $axis: [
                            for $breakdown in $definition-model.Breakdowns.$axis[]
                            return resolution:convert-breakdown($breakdown,
                                                                $components,
                                                                $definition-model.ParentChildOrder,
                                                                $concepts,
                                                                $options)
                        ]
                    }
                |}
            }
        ],
        GlobalConstraintSet: $definition-model.TableFilters,
        GlobalConstraintLabels: {|
            for $dimension in keys($definition-model.TableFilters)
            let $dimension-label as string* := resolution:metadata($components, $dimension).Label[1]
            let $value := $definition-model.TableFilters.$dimension
            let $value-label as string* := if($value instance of string) then resolution:metadata($components, $value).Label else ()
            return ({ $dimension: $dimension-label[1] }[exists($dimension-label)],
                    { $value: $value-label[1] }[exists($value-label)]
                    )
        |},
        DimensionDefaults: {|
            for $dimension as string in keys($hypercubes.Aspects)
            let $hypercube-default as atomic? := $hypercubes.Aspects.$dimension.Default[1]
            where exists($hypercube-default)
            return {
                $dimension: $hypercube-default
            }
        |}
    }
};

jsoniq version "1.0";

module namespace resolution = "http://28.io/modules/xbrl/resolution";

import module namespace components = "http://28.io/modules/xbrl/components";
import module namespace concepts = "http://28.io/modules/xbrl/concepts";
import module namespace facts = "http://28.io/modules/xbrl/facts";
import module namespace hypercubes = "http://28.io/modules/xbrl/hypercubes";
import module namespace networks = "http://28.io/modules/xbrl/networks";

(: TODOs
- Options for relationship networks (formulaAxis, depth)
:)

(:~
 : Converts a definition breakdown to a structural breakdown
 :
 : @param $breakdown a breandowk
 : @param $components a sequence of components
 : @param $parent-child-order "parentFirst" or "childrenFirst"
 : @param $concepts the concept objects (for inferring the labels)
 : @param $options the option object
 :
 : @error resolution:UNKNOWN-DEFINITION-NODE-KIND if a definition node kind
 : is unrecognized.
 : @error resolution:UNRESOLVED-CONCEPT-RELATIONSHIP if a root concept
 : cannot be resolved.
 : @error resolution:UNRESOLVED-DIMENSION-RELATIONSHIP if a root member
 : cannot be resolved.
 : @error resolution:NON-ABSTRACT-MERGE-NODE if a rule node is merge,
 : but non-abstract.
 :
 : @return the converted, structural breakdown.
 :)
declare %private function resolution:convert-breakdown(
    $breakdown as object,
    $components as object*,
    $parent-child-order as string?,
    $concepts as object*,
    $options as object?) as object
{
    let $parent-child-order as string? := ($breakdown.ParentChildOrder, $parent-child-order)[1]

    let $labels as array := $breakdown.BreakdownLabels

    let $unbalanced-trees as object* := resolution:convert-definition-nodes(
        $breakdown.BreakdownTrees[],
        $components,
        $parent-child-order,
        $concepts,
        $options
    )
    let $balanced-trees as object* := resolution:height-balance($unbalanced-trees)

    return {
        BreakdownLabels: $labels,
        BreakdownTrees: [ $balanced-trees ]
    }
};

(:~
 : Converts each definition node to one or more structural nodes
 :
 : @param $definition-nodes some definition nodes.
 : @param $components a sequence of components
 : @param $parent-child-order "parentFirst" or "childrenFirst"
 : @param $concepts the concept objects (for inferring the labels)
 : @param $options the options object
 :
 : @error resolution:UNKNOWN-DEFINITION-NODE-KIND if a definition node kind
 : is unrecognized.
 : @error resolution:UNRESOLVED-CONCEPT-RELATIONSHIP if a root concept
 : cannot be resolved.
 : @error resolution:UNRESOLVED-DIMENSION-RELATIONSHIP if a root member
 : cannot be resolved.
 : @error resolution:NON-ABSTRACT-MERGE-NODE if a rule node is merge,
 : but non-abstract.
 :
 : @return the converted structural nodes.
 :)
declare %private function resolution:convert-definition-nodes(
    $definition-nodes as object*,
    $components as object*,
    $parent-child-order as string?,
    $concepts as object*,
    $options as object?) as object*
{
    for $definition-node as object in $definition-nodes
    let $parent-child-order as string? := ($definition-node.ParentChildOrder, $parent-child-order)[1]
    for $converted-node in
      switch($definition-node.Kind)
      case "Rule" return resolution:convert-rule-node(
          $definition-node,
          $components,
          $parent-child-order,
          $concepts,
          $options)
      case "Aspect" return resolution:convert-aspect-node(
          $definition-node,
          $components,
          $parent-child-order,
          $concepts,
          $options)
      case "ConceptRelationship" return resolution:convert-concept-relationship-node(
          $definition-node,
          $components,
          $parent-child-order,
          $concepts,
          $options)
      case "DimensionRelationship" return resolution:convert-dimension-relationship-node(
          $definition-node,
          $components,
          $parent-child-order,
          $concepts)
      default return error(
          QName("resolution:UNKNOWN-DEFINITION-NODE-KIND"),
          "Unknown definition node kind: $definition-node.Kind")
    return if(exists($definition-node.Id))
           then copy $c := $converted-node
                modify for $node in ($c, descendant-objects($c).Children[])
                       return insert json { Id: $definition-node.Id } into $node
                return $c
           else $converted-node
};

(:~
 : Retrieves the labels from the components' cache (default language)
 : or from the remove collection cache.
 :
 : @param $concept-names a sequence of concept names.
 : @param $components a sequence of components
 : @param $concepts the concept objects (for inferring the labels)
 : @param $label-role the desired label role
 : @param $options the options object
 :
 : @return the labels
 :)
declare %private function resolution:labels(
    $concept-names as string*,
    $components as object*,
    $concepts as object*,
    $label-role as string,
    $options as object?) as string*
{
    let $components-with-the-language-as-default :=
        $components[not $$.$components:DEFAULT-LANGUAGE ne $options.Language]

    let $labels-from-local-metadata as string* :=
        let $default-hypercubes as object* :=
            hypercubes:hypercubes-for-components($components-with-the-language-as-default, "xbrl:DefaultHypercube")
        for $local-metadata as object in
            descendant-objects($default-hypercubes.Aspects)
        let $local-metadata-name := $local-metadata.Name
        let $local-metadata-preferred-label-role as string := ($local-metadata.PreferredLabelRole, $concepts:STANDARD_LABEL_ROLE)[1]
        where $local-metadata-name = $concept-names and
              $local-metadata-preferred-label-role eq $label-role
        return
            $local-metadata.Label

    let $labels-from-concepts-collection as string* :=
        if(empty($labels-from-local-metadata))
        then
            concepts:labels-for-components(
                $concept-names,
                $components,
                $label-role,
                ($options.Language, "en-US")[1],
                $concepts,
                ())
        else ()

    return ($labels-from-local-metadata, $labels-from-concepts-collection)
 };

(:~
 : Converts a rule definition node to one or more structural nodes.
 : A rule node restricts a dimension to a value.
 :
 : @param $definition-node a definition node.
 : @param $components a sequence of components
 : @param $parent-child-order "parentFirst" or "childrenFirst"
 : @param $concepts the concept objects (for inferring the labels)
 : @param $options the options object
 :
 : @error resolution:NON-ABSTRACT-MERGE-NODE if a rule node is merge,
 : but non-abstract.
 :
 : @return the converted structural nodes.
 :)
declare %private function resolution:convert-rule-node(
    $definition-node as object,
    $components as object*,
    $parent-child-order as string?,
    $concepts as object*,
    $options as object?) as object*
{
    let $main-members := values(values($definition-node.AspectRulesSet))

    let $labels := (
        $definition-node.Labels[],
        resolution:labels(
            $main-members,
            $components,
            $concepts,
            $concepts:STANDARD_LABEL_ROLE,
            $options)
    )

    let $children := resolution:convert-definition-nodes(
        $definition-node.Children[],
        $components,
        $parent-child-order,
        $concepts,
        $options)
    let $roll-up := {
        Labels: [ ],
        ConstraintSets : {
            "": { }

        },
        RollUp: true
    }
    let $constraint-sets := {|
        for $tag in keys($definition-node.AspectRulesSet)
        return {
            $tag: {|
                for $aspect in keys($definition-node.AspectRulesSet.$tag)
                return {
                    $aspect: $definition-node.AspectRulesSet.$tag.$aspect
                }
            |}
        }
    |}
    let $merged-children :=
        for $child in $children
        return copy $c := $child
        modify for $tag in keys($c.ConstraintSets)
               return replace value of json $c.ConstraintSets.$tag with facts:merge-objects(
                    $c.ConstraintSets.$tag,
                    $constraint-sets.$tag,
                    true)
        return $c
    return switch(true)
           case not $definition-node.Abstract and $definition-node.Merge
                return error(QName("resolution:NON-ABSTRACT-MERGE-NODE"), "A definition rule node cannot be non-abstract and merged.")
           case $definition-node.Merge return $merged-children
           case $definition-node.Abstract return {|
                {
                    Labels: [  $labels ],
                    ConstraintSets: $constraint-sets
                },
                if(exists($definition-node.TagSelectors))
                then {
                    TagSelectors: $definition-node.TagSelectors
                }
                else (),
                if(exists($children)) then {
                    Children: [ $children ]
                }
                else ()
           |}
            default return {|
                {
                    Labels: [  $labels ],
                    ConstraintSets: $constraint-sets
                },
                if(exists($definition-node.TagSelectors))
                then {
                    TagSelectors: $definition-node.TagSelectors
                }
                else (),
                if(exists($children))
                then {
                    Children: switch(true)
                              case $parent-child-order eq "parentFirst" return [$roll-up, $children]
                              default return [$children, $roll-up]
                }
                else (),
                if($definition-node.IsTotal)
                then { IsTotal: true }
                else ()
            |}
};

(:~
 : Convert an aspect definition node to one or more structural nodes.
 : An aspect nodes will expand to all values found in the fact pool during
 : the layouting stage.
 :
 : @param $definition-node a definition node.
 : @param $components a sequence of components
 : @param $parent-child-order "parentFirst" or "childrenFirst"
 : @param $concepts the concept objects (for inferring the labels)
 : @param $options the options object
 :
 : @return the converted structural node.
 :)
declare %private function resolution:convert-aspect-node(
    $definition-node as object,
    $components as object*,
    $parent-child-order as string?,
    $concepts as object*,
    $options as object?) as object
{
    let $children :=  resolution:convert-definition-nodes(
        $definition-node.Children[],
        $components,
        $parent-child-order,
        $concepts,
        $options)
    let $constrained-aspect := $definition-node.Aspect
    return {|
        {
            Open: true,
            Aspect: $constrained-aspect
        },
        if ($children)
        then { Children: [ $children ] }
        else ()
    |}
};

(:~
 : Convert a concept relationship definition node to one or more structural nodes.
 : A concept relationship node will automatically expand a network to a hierarchy
 : of structural nodes.
 :
 : @param $definition-node a definition node.
 : @param $components a sequence of components
 : @param $parent-child-order "parentFirst" or "childrenFirst"
 : @param $concepts the concept objects (for inferring the labels)
 :
 : @error resolution:UNRESOLVED-CONCEPT-RELATIONSHIP if the root concept
 : cannot be resolved.
 :
 : @return the converted structural node.
 :)
declare %private function resolution:convert-concept-relationship-node(
    $definition-node as object,
    $components as object*,
    $parent-child-order as string?,
    $concepts as object*,
    $options as object?) as object
{
    let $link-role := $definition-node.LinkRole
    let $link-name := $definition-node.LinkName
    let $arc-role := $definition-node.ArcRole
    let $arc-name := $definition-node.ArcName
    let $root := $definition-node.RelationshipSource
    let $network as object? := networks:networks-for-components($components)[
        $$.LinkRole eq $link-role and
        $$.LinkName eq $link-name and
        $$.ArcRole eq $arc-role and
        $$.ArcName eq $arc-name
    ]
    let $subnetwork := descendant-objects($network.Trees)[$$.Name eq $root]
    return if(exists($subnetwork))
    then resolution:expand-concept-network($subnetwork, $components, $parent-child-order, $concepts, $options)
    else error(QName("resolution:UNRESOLVED-CONCEPT-RELATIONSHIP"), $root || ": The concept root could not be resolved.")
};

(:~
 : Helper, recursive function for resolution:convert-concept-relationship-node#3
 :
 : @param $network a network to expand.
 : @param $components a sequence of components.
 : @param $parent-child-order "parentFirst" or "childrenFirst"
 : @param $concepts the concept objects (for inferring the labels)
 :
 : @return the converted structural nodes.
 :)
declare %private function resolution:expand-concept-network(
    $network as object,
    $components as object*,
    $parent-child-order as string?,
    $concepts as object*,
    $options as object?) as object*
{
    let $concept := $network.Name
    let $default-hypercube := hypercubes:hypercubes-for-components($components, "xbrl:DefaultHypercube")
    let $concept-metadata := $default-hypercube.Aspects."xbrl:Concept".Domains."xbrl:ConceptDomain".Members.$concept[1]
    let $label :=
        if(not $options.Language != $components.$components:DEFAULT-LANGUAGE)
        then $network.Label
        else
        resolution:labels(
            $concept,
            $components,
            $concepts,
            ($network.PreferredLabelRole, $concepts:STANDARD_LABEL_ROLE)[1],
            ())
    return
    {|
        {
            Labels: [ $label ],
            ConstraintSets: {
                "" : { "xbrl:Concept" : $concept }
            }
        },

        switch($network.PreferredLabelRole)
        case "http://www.xbrl.org/2003/role/totalLabel"
        return {
            IsTotal: true
        }
        case "http://www.xbrl.org/2009/role/negatedLabel"
        return {
            IsNegated: true
        }
        case "http://www.xbrl.org/2009/role/negatedTerseLabel"
        return {
            IsNegated: true
        }
        case "http://www.xbrl.org/2003/role/periodStartLabel"
        return {
            TagSelectors: [ "table.periodStart" ]
        }
        case "http://www.xbrl.org/2003/role/periodEndLabel"
        return {
            TagSelectors: [ "table.periodEnd" ],
            IsTotal: true
        }
        default return (),

        let $sub-networks := (values($network.To), $network.To[])
        let $converted-subnetworks :=
            for $sub-network in $sub-networks
            let $order := $sub-network.Order
            order by $order
            return
                resolution:expand-concept-network(
                        $sub-network,
                        $components,
                        $parent-child-order,
                        $concepts,
                        $options
                    )
        let $roll-up :=
            if($concept-metadata.IsAbstract)
            then ()
            else {
                Labels: [],
                RollUp: true
            }
        where exists($converted-subnetworks)
        return {
            Children: [
                switch($parent-child-order)
                case "parentFirst" return ($roll-up, $converted-subnetworks)
                default return ($converted-subnetworks, $roll-up)
            ]
        }

    |}
};

(:~
 : Convert a dimension relationship definition node to one or more structural nodes.
 : A dimension relationship node will automatically expand a network to a hierarchy
 : of structural nodes.
 : @param $definition-node a definition node.
 : @param $components a sequence of components
 : @param $parent-child-order "parentFirst" or "childrenFirst"
 : @param $concepts the concept objects (for inferring the labels)
 :
 : @error resolution:UNRESOLVED-CONCEPT-RELATIONSHIP if the root member
 : cannot be resolved.
 :
 : @return the converted structural node.
 :)
declare %private function resolution:convert-dimension-relationship-node(
    $definition-node as object,
    $components as object*,
    $parent-child-order as string?,
    $concepts as object*) as object
{
    let $link-role := $definition-node.LinkRole
    let $dimension := $definition-node.Dimension
    let $root := $definition-node.RelationshipSource
    let $hypercubes as object* := hypercubes:hypercubes-for-components($components[$$.Role eq $link-role])
    let $subnetwork as object := descendant-objects($hypercubes.Aspects.$dimension)[$$.Name eq $root][1]
    return if(exists($subnetwork))
    then resolution:expand-dimension-network($dimension, $subnetwork, $components, $parent-child-order, $concepts)
    else error(QName("resolution:UNRESOLVED-DIMENSION-RELATIONSHIP"), $root || ": The dimension member root could not be resolved.")
};

(:
    Helper, recursive function for resolution:convert-dimension-relationship-node#3
:)
declare function resolution:expand-dimension-network(
    $dimension as string,
    $network as object,
    $components as object*,
    $parent-child-order as string?,
    $concepts as object*) as object
{
    let $value := $network.Name
    let $label :=
        resolution:labels(
            $value,
            $components,
            $concepts,
            ($network.PreferredLabelRole, $concepts:STANDARD_LABEL_ROLE)[1],
            ())
    return
    {|
        {
            Labels: [ $label],
            ConstraintSets: {
                "" : { $dimension : $value }
            }
        },
        let $sub-networks := values($network.Members)
        let $converted-subnetworks :=
            for $sub-network in $sub-networks
            return resolution:expand-dimension-network(
                        $dimension,
                        $sub-network,
                        $components,
                        $parent-child-order,
                        $concepts
                )
        let $roll-up :={
            Labels: [],
            RollUp: true
        }
        where exists($converted-subnetworks)
        return { Children: [ $converted-subnetworks, $roll-up ] }
    |}
};

(:
    Helper function that returns the depth of breakdown trees set.
:)
declare function resolution:depth($axis-breakdown-trees as object*) as integer
{
    switch(true)
    case empty($axis-breakdown-trees) return 0
    case empty($axis-breakdown-trees.Children[]) return 1
    default return max($axis-breakdown-trees.Children[] ! (1 + resolution:depth($$)))
};

(:~
 : Helper function that height-balances a breakdown trees set,
 : by adding roll-up nodes to get a uniform depth.
 :
 : @param $axis-breakdown-trees the breakdown trees for an axis
 :
 : @return the balanced breakdown trees.
 :)
declare function resolution:height-balance($axis-breakdown-trees as object*) as object*
{
    let $depth := resolution:depth($axis-breakdown-trees)
    return resolution:height-balance($axis-breakdown-trees, $depth)
};

(:~
 : Helper, recursive function for resolution:height-balance#1.
 :
 : @param $axis-breakdown-trees the breakdown trees for an axis
 : @parem the depth at which these trees should get balanced.
 :
 : @return the balanced breakdown trees.
 :)
declare function resolution:height-balance($axis-breakdown-trees as object*, $desired-depth as integer) as object*
{
  let $roll-up-cell := {
    CellLabels: [],
    ConstraintSets: {"" : {}},
    RollUp: true
  }
  return
    for $tree in $axis-breakdown-trees
    return switch(true)
           case $desired-depth gt 1 and empty($tree.Children)
           return copy $t := $tree
                  modify insert json {
                    Children: [
                      resolution:height-balance($roll-up-cell, $desired-depth - 1)
                    ]
                  } into $t
                  return $t
                case $desired-depth gt 1 and exists($tree.Children)
                  return copy $t := $tree
                         modify replace value of json $t.Children with [
                           $t.Children[] ! resolution:height-balance($$, $desired-depth - 1)
                         ]
                         return $t
                case $desired-depth eq 1 and empty($tree.Children)
                  return $tree
                default
                  return error(QName("resolution:UNFORESEEN-ERROR"), "An error occurred while height-balancing")
};

(:~
 : Retrieves the metadata for some members from a component.
 :
 : @param $components a sequence of components.
 : @param $member-names the names of the members for which to retrieve the metadata.
 :
 : @return the metadata for the supplied members.
 :)
declare %private function resolution:metadata(
    $components as object*,
    $member-names as string*) as object*
{
    let $default-hypercube := hypercubes:hypercubes-for-components($components, "xbrl:DefaultHypercube")
    return descendant-objects($default-hypercube.Aspects)[$$.Name = $member-names][1]
};

(:~
  Resolves a definition model to a structural model, given a component.

  @param $definition-model A definition mode, in 28msec's proprietary JSON format.
  @param $component A component, in 28msec's proprietary JSON format.

  @error resolution:UNFORESEEN-ERROR Something went wrong, contact us.
  @error resolution:UNKNOWN-DEFINITION-NODE-KIND A definition node was not recognized.

  @return a structural model
:)
declare function resolution:resolve(
    $definition-model as object,
    $components as object*) as object
{
    resolution:resolve($definition-model, $components, ())
};

(:~
 : Resolves a definition model to a structural model, given a component.
 :
 : @param $definition-model A definition mode, in 28msec's proprietary JSON format.
 : @param $component A component, in 28msec's proprietary JSON format.
 : @param $options Optional parameters among which
 : <ul>
 :   <li>Hypercube: override the components' hypercubes with the provided hypercube
 :      (this will only affect the default values used later in the layout pipeline).</li>
 :    <li>Language: override the components' default language in the rendering.</li>
 : </ul>
 :
 : @error resolution:UNFORESEEN-ERROR Something went wrong, contact us.
 : @error resolution:UNKNOWN-DEFINITION-NODE-KIND A definition node was not recognized.
 : @error resolution:UNRESOLVED-CONCEPT-RELATIONSHIP if the root concept
 : cannot be resolved.
 : @error resolution:UNRESOLVED-DIMENSION-RELATIONSHIP if the root member
 : cannot be resolved.
 : @error resolution:NON-ABSTRACT-MERGE-NODE if a rule node is merge,
 : but non-abstract.
 :
 : @return a structural model
 :)
declare function resolution:resolve(
    $definition-model as object,
    $components as object*,
    $options as object?) as object
{
    let $concepts as object* := concepts:concepts-for-components(
        $concepts:ALL_CONCEPT_NAMES,
        $components)
    let $hypercubes as object* :=
        if(exists($options.Hypercube))
        then $options.Hypercube
        else values($components.Hypercubes)
    return {
        ModelKind: "StructuralModel",
        TableSetLabels: $definition-model.Labels,
        Component: {
            Role: $components.Role[1],
            Label: $components.Label[1]
        },
        TableSet : [
            {
                Breakdowns: {|
                    for $axis in keys($definition-model.Breakdowns)
                    return {
                        $axis: [
                            for $breakdown in $definition-model.Breakdowns.$axis[]
                            return resolution:convert-breakdown($breakdown,
                                                                $components,
                                                                $definition-model.ParentChildOrder,
                                                                $concepts,
                                                                $options)
                        ]
                    }
                |}
            }
        ],
        GlobalConstraintSet: $definition-model.TableFilters,
        GlobalConstraintLabels: {|
            for $dimension in keys($definition-model.TableFilters)
            let $dimension-label as string* := resolution:metadata($components, $dimension).Label[1]
            let $value := $definition-model.TableFilters.$dimension
            let $value-label as string* := if($value instance of string) then resolution:metadata($components, $value).Label else ()
            return ({ $dimension: $dimension-label[1] }[exists($dimension-label)],
                    { $value: $value-label[1] }[exists($value-label)]
                    )
        |},
        DimensionDefaults: {|
            for $dimension as string in keys($hypercubes.Aspects)
            let $hypercube-default as atomic? := $hypercubes.Aspects.$dimension.Default[1]
            where exists($hypercube-default)
            return {
                $dimension: $hypercube-default
            }
        |}
    }
};