#!/usr/bin/env python3
# coding: utf-8
#
# Copyright 2020 by Leipzig University Library, http://ub.uni-leipzig.de
#                   The Finc Authors, http://finc.info
#                   Robert Schenk, <robert.schenk@uni-leipzig.de>
#
# This file is part of some open source application.
#
# Some open source application is free software: you can redistribute
# it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, either
# version 3 of the License, or (at your option) any later version.
#
# Some open source application is distributed in the hope that it will
# be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
# of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
#
# @license GPL-3.0+ <http://spdx.org/licenses/GPL-3.0+>

"""

Source: Online Contents (OLC)
SID: 68
Ticket: #5163, #6743, #9354, #10294, #16196
Origin: HTTP

"""


import os
import re
import sys
import json

import marcx
from siskin.configuration import Config
from siskin.arguments import FincArgumentParser


def get_field(oldrecord, field, multivalue=True):
    try:
        field = oldrecord[field]
    except:
        return ""

    if isinstance(field, list) and multivalue == False:
        return field[0]
    else:
        return field


def build_field(oldrecord, newrecord, oldfield, newfield, multivalue=True):
    try:
        field = oldrecord[oldfield]
    except:
        field = ""

    if field and multivalue:
        if not isinstance(field, list):
            field = [field]
    elif field and not multivalue:
        if isinstance(field, list):
            field = field[0]

    if field:
        newrecord[newfield] = field


##################################################################################
# 1. Parse arguments and prepare outputfile
##################################################################################

SID = "68"

fip = FincArgumentParser()

# Get arguments
inputfile = fip.args.inputfile
outputformat = fip.args.outputformat

# Generates string for outputfilename, example: 196-output-20200701.fincmarc.mrc
outputfilename = fip.outputfilename(SID)

# Removes n old input and outputfiles as specified in input-hist-size and output-hist-size
fip.remove_old_outputfiles(SID)
fip.remove_old_inputfiles(SID)

outputfile = open(outputfilename, "w")


##################################################################################
# 2. Get input data
################################################################################

if not inputfile:
    inputfile = fip.inputfilename(SID)
    os.system("""solrdump -k -verbose -server https://findex.ubl-proxy.slub-dresden.de/index/SLUB -q "collection_details:SSG-OLC-FTH OR
                 collection_details:SSG-OLC-MKW OR collection_details:SSG-OLC-BUB" -fl "id,title,physical,issn,container_title,
                 container_issue,container_volume,container_start_page,publisher,publish_place,lang_code,publishDateSort,format,
                 abstract,isfreeaccess_txt,author2,url,topic_facet,collection_details" | jq . -c > %s""" % inputfile)

inputfile = open(inputfile, "r")


##################################################################################
# 3. Process data
##################################################################################

for oldrecord in inputfile:

    oldrecord = json.loads(oldrecord)
    newrecord = {}

    # Finc-ID
    old_id = get_field(oldrecord, "id")
    finc_id = "ai-68-" + old_id
    newrecord["finc.id"] = finc_id

    # Mega Collections
    sets = get_field(oldrecord, "collection_details")
    mega_collections = []
    institutions = []

    if "SSG-OLC-MKW" in sets:
        mega_collections.append("OLC SSG Medien- / Kommunikationswissenschaft")
        institutions.append("DE-15-FID")

    if "SSG-OLC-FTH" in sets:
        mega_collections.append("OLC SSG Film / Theater")
        if "DE-15-FID" not in institutions:
            institutions.append("DE-15-FID")

    if "SSG-OLC-BUB" in sets:
        mega_collections.append("OLC SSG Informations-, Buch- und Bibliothekswesen")
        institutions.append("FID-BBI-DE-23")

    newrecord["finc.mega_collection"] = mega_collections
    newrecord["x.labels"] = institutions

    # Source-ID
    newrecord["finc.source_id"] = "68"

    # Author
    authors = get_field(oldrecord, "author2")
    if  isinstance(authors, list):
        aut = []
        for author in authors:
            aut.append({"rft.au": author})
        newrecord["authors"] = aut

    # Publish date
    date = get_field(oldrecord, "publishDateSort", multivalue=False)
    if len(date) == 4:
        date = date + "-01-01T00:00:00Z"
        newrecord["x.date"] = date

    # Format mapping
    format = get_field(oldrecord, "format", multivalue=False)

    if format == "Journal" or format == "eJournal":
        newrecord["finc.format"] = "Journal"

    elif format == "Article" or format == "electronic Article":
        newrecord["finc.format"] = "Article"

    elif format == "Monograph Series":
        newrecord["finc.format"] = "Serial"

    elif format == "Serial Volume":
        newrecord["finc.format"] = "Book"

    # Remaining fields
    build_field(oldrecord, newrecord, "title", "rft.atitle", multivalue=False)
    build_field(oldrecord, newrecord, "title_sub", "x.subtitle", multivalue=False)
    build_field(oldrecord, newrecord, "container_title", "rft.jtitle", multivalue=False)
    build_field(oldrecord, newrecord, "container_issue", "rft.issue", multivalue=False)
    build_field(oldrecord, newrecord, "container_volume", "rft.volume", multivalue=False)
    build_field(oldrecord, newrecord, "container_start_page", "rft.spage", multivalue=False)
    build_field(oldrecord, newrecord, "lang_code", "languages")
    build_field(oldrecord, newrecord, "publisher", "rft.pub")
    build_field(oldrecord, newrecord, "publish_place", "rft.place")
    build_field(oldrecord, newrecord, "issn", "rft.issn")
    build_field(oldrecord, newrecord, "abstract", "abstract", multivalue=False)
    #build_field(oldrecord, newrecord, "physical", "rft.tpages", multivalue=False)
    newrecord["rft.genre"] = "article"

    # Write one JSON-record
    outputfile.write(json.dumps(newrecord) + "\n")

inputfile.close()
outputfile.close()
