{# 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
    ISBN13 as product_id,
    work_id,
    work_family_id,
    onix.title as title,
    CAST(onix.published_year as INT64) as published_year,
    month.month,
    STRUCT((SELECT SUM(value) FROM UNNEST(month.google_analytics.unique_views.country)) as unique_views) as google_analytics,
    STRUCT((SELECT SUM(count) FROM UNNEST(month.crossref_events)) as count) as crossref_events,
    month.google_books_traffic,
    month.google_books_sales,
    STRUCT((SELECT SUM(Total_Item_Requests) FROM UNNEST(month.jstor_country)) as Total_Item_Requests) as jstor,
    STRUCT(
        month.oapen_irus_uk.version,
        month.oapen_irus_uk.title_requests,
        month.oapen_irus_uk.total_item_investigations,
        month.oapen_irus_uk.total_item_requests,
        month.oapen_irus_uk.unique_item_investigations,
        month.oapen_irus_uk.unique_item_requests
    ) as oapen_irus_uk,
    STRUCT(month.ucl_discovery.total_downloads) as ucl_discovery
FROM `{{ project_id }}.{{ dataset_id }}.book_product{{ release.strftime('%Y%m%d') }}`, UNNEST(months) as month
WHERE month.oapen_irus_uk IS NOT NULL OR month.google_books_traffic IS NOT NULL OR month.google_books_sales IS NOT NULL