{# Copyright 2020 Curtin University
#
# 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.

# Author: Richard Hosking #}

SELECT
    oapen.identifier.isbn as ISBN13,
    oapen.identifier.doi as Doi,
    "Digital download and online" as ProductForm,
    CAST(NULL as STRING) as EditionNumber,

    [STRUCT(
        [STRUCT(dc.title.value[SAFE_OFFSET(0)] as TitleText, dc.title.alternative as TitleWithoutPrefix)] as TitleElements,
        CAST(NULL as STRING) as TitleType,
        CAST(NULL as STRING) as TitleStatement
    )] as TitleDetails,

    ARRAY(
        SELECT AS STRUCT
            "Publication date" as PublishingDateRole,
            CAST(FORMAT_DATETIME("%Y%m%d", published) as INT64) as `Date`
        FROM UNNEST(dc.date.issued) as published
    )  as PublishingDates,

    ARRAY_CONCAT(
        ARRAY(
            SELECT AS STRUCT
                "BIC_subject_category" as SubjectSchemeIdentifier,
                code as SubjectCode,
                ARRAY<STRING>[] as SubjectHeadingText
            FROM UNNEST(dc.subject.classification_code) as code
        ),
        ARRAY(
            SELECT AS STRUCT
                "Keywords" as SubjectSchemeIdentifier,
                CAST(NULL as STRING) as SubjectCode,
                IF(
                    ARRAY_TO_STRING(ARRAY_AGG(code), '; ') IS NOT NULL,
                    [ARRAY_TO_STRING(ARRAY_AGG(code), '; ')],
                    ARRAY<STRING>[]
                ) as SubjectHeadingText
            FROM UNNEST(dc.subject.other) as code
        )
    ) as Subjects,

    ARRAY(
        SELECT AS STRUCT
            SPLIT(author, '::')[SAFE_OFFSET(0)] as PersonName,
            SPLIT(author, '::')[SAFE_OFFSET(1)] as ORCID
        FROM UNNEST(dc.contributor.author) as author
    )  as Contributors,

FROM `{{ project_id }}.{{ dataset_id }}.{{ table_id }}` as onix