{# 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 #}

WITH google_analytics as (
    {% if google_analytics %}
    SELECT
        {{ google_analytics_isbn }} as ISBN,
        release_date,
        "google_analytics" as source
    FROM `{{ project_id }}.{{ dataset_id }}.{{ google_analytics_table }}_unmatched_{{ google_analytics_isbn }}{{ release.strftime('%Y%m%d') }}`
    {% else %}
    SELECT
        CAST(NULL as STRING) as ISBN,
        CAST(NULL as DATE) as release_date,
        "google_analytics" as source
    {% endif %}
),

google_books as (
    {% if google_books %}
    SELECT
        {{ google_books_isbn }} as ISBN,
        release_date,
        "google_books" as source
    FROM `{{ project_id }}.{{ dataset_id }}.{{ google_books_table }}_unmatched_{{ google_books_isbn }}{{ release.strftime('%Y%m%d') }}`
    {% else %}
    SELECT
        CAST(NULL as STRING) as ISBN,
        CAST(NULL as DATE) as release_date,
        "google_books" as source
    {% endif %}
),

jstor as (
    {% if jstor %}
    SELECT
        {{ jstor_isbn }} as ISBN,
        release_date,
        "jstor" as source
    FROM `{{ project_id }}.{{ dataset_id }}.{{ jstor_table }}_unmatched_{{ jstor_isbn }}{{ release.strftime('%Y%m%d') }}`
    {% else %}
    SELECT
        CAST(NULL as STRING) as ISBN,
        CAST(NULL as DATE) as release_date,
        "jstor" as source
    {% endif %}
),

oapen as (
    {% if oapen %}
    SELECT
        {{ oapen_isbn }} as ISBN,
        release_date,
        "oapen" as source
    FROM `{{ project_id }}.{{ dataset_id }}.{{ oapen_table }}_unmatched_{{ oapen_isbn }}{{ release.strftime('%Y%m%d') }}`
    {% else %}
    SELECT
        CAST(NULL as STRING) as ISBN,
        CAST(NULL as DATE) as release_date,
        "oapen" as source
    {% endif %}
),

all_un_matched as (
SELECT * FROM google_analytics
    UNION ALL
SELECT * FROM google_books
    UNION ALL
SELECT * FROM jstor
    UNION ALL
SELECT * FROM oapen
)

SELECT
    ISBN,
    release_date,
    "google_analytics" in UNNEST(ARRAY_AGG(source)) as in_google_analytics,
    "google_books" in UNNEST(ARRAY_AGG(source)) as in_google_books,
    "jstor" in UNNEST(ARRAY_AGG(source)) as in_jstor,
    "oapen" in UNNEST(ARRAY_AGG(source)) as in_oapen,
FROM all_un_matched
WHERE ISBN IS NOT NULL
GROUP BY ISBN, release_date