#!/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: OER OPAL
SID: 172
Ticket: #14442
Origin: Cloud

"""


import os
import sys
import csv

import marcx
import pymarc
from siskin.configuration import Config
from siskin.mappings import formats
from siskin.arguments import FincArgumentParser
from siskin.utils import check_isbn, check_issn, marc_build_field_008


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

SID = "172"

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 inputfiles and outputfiles as specified in input-hist-size and output-hist-size
fip.remove_old_outputfiles(SID)
fip.remove_old_inputfiles(SID)

# Set output format for MARC record
if outputformat == "xml":
    outputfile = pymarc.XMLWriter(open(outputfilename, "wb"))
else:
    outputfile = open(outputfilename, "wb")


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

if not inputfile:
    inputfile = fip.inputfilename(SID)
    config = Config.instance()
    user = config.get(SID, "user")
    password = config.get(SID, "password")
    url = config.get(SID, "url")
    os.system('wget -O %s --user=%s --password=%s "%s"' % (inputfile, user, password, url))

inputfile = open(inputfile, "r", encoding="utf-16")
records = csv.reader(inputfile, delimiter="\t")


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

for fields in records:

    if fields[0] == "id":
        continue

    marcrecord = marcx.Record(force_utf8=True)
    marcrecord.strict = False

    # Format for entire source
    format = "Article"

    # Leader
    leader = formats[format]["Leader"]
    marcrecord.leader = leader

    # Identifier
    f001 = fields[0]
    f001 = f001.split("-")
    f001 = f001[2]
    marcrecord.add("001", data="finc-172-" + f001)

    # Access facet
    f007 = formats[format]["e007"]
    marcrecord.add("007", data=f007)

    # Periodicity
    language = fields[11]
    if language == "engrish":
        language = "eng"
    elif language == "English":
        language = "eng"
    elif language == "Deutsch":
        language = "ger"
    year = fields[9]
    year = year.replace("\n", "")
    periodicity = formats[format]["008"]
    f008 = marc_build_field_008(year, periodicity, language)
    marcrecord.add("008", data=f008)

    # Language
    if len(language) == 3:
        marcrecord.add("041", a=language)

    # First creator
    persons = fields[6]
    if persons:
        num_persons = persons.split(" ")
        if len(num_persons) > 3:
            more_than_one_persons = True
        else:
            more_than_one_persons = False
        if more_than_one_persons and "; " in persons:
            persons = persons.split("; ")
        elif more_than_one_persons and ", " in persons:
            persons = persons.split(", ")
        else:
            persons = persons.split("*")
        f100a = persons[0]
        marcrecord.add("100", a=f100a)

    # Title statement
    f245a = fields[4]
    f245b = fields[1]
    if not f245a:
        f245a = fields[1]
        f245b = ""
    if f245a == f245b:
        f245b = ""
    f245c = fields[6]
    marcrecord.add("245", a=f245a, b=f245b, c=f245c)

    # Imprint
    f260b = fields[8]
    f260c = fields[9]
    f260c = f260c.replace("\n", "")
    if len(f260c) == 4:
        marcrecord.add("260", b=f260b, c=f260c)

    # RDA-content
    f336b = formats[format]["336b"]
    marcrecord.add("336", b=f336b)

    # RDA-carrier
    f338b = formats[format]["338b"]
    marcrecord.add("338", b=f338b)

    # Legal note
    f540a = fields[2]
    marcrecord.add("540", a=f540a, u="http://creativecommons.org/licenses/by/4.0/")

    # Subject headings
    f650a = fields[12]
    marcrecord.add("650", a=f650a)

    # GND-content and -carrier
    f655a = formats[format]["655a"]
    f6552 = formats[format]["6552"]
    marcrecord.add("655", a=f655a, _2=f6552)

    # Additional creator
    for person in persons[1:]:
        marcrecord.add("700", a=person)

    # Link to fulltext
    f856u = fields[3]
    marcrecord.add("856", q="text/html", _3="Link zur Ressource", u=f856u)

    # SWB-content
    f935c = formats[format]["935c"]
    marcrecord.add("935", c=f935c)

    # Collection and sealing
    marcrecord.add("980", a=f001, b="172", c="sid-172-col-opal")

    # Write record to file
    if outputformat == "xml":
        outputfile.write(marcrecord)
    else:
        outputfile.write(marcrecord.as_marc())

inputfile.close()
outputfile.close()
