#!/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: Miningscout
SID: 194
Ticket: #17428
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, marc_get_languages


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

SID = "194"

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" --no-check-certificate' % (inputfile, user, password, url))

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


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

for fields in records:

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

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

    # Format mapping
    format = fields[1]
    if format == "Video":
        format = "Online-Video"
    else:
        sys.exit("Unknown format: " + format)

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

    # Identifier
    f001 = fields[0]
    marcrecord.add("001", data="194-" + f001)

    # Access type (online or physical)
    f007 = formats[format]["e007"]
    marcrecord.add("007", data=f007)

    # Periodicity
    language = fields[6]
    if language:
        if language == "Deutsch":
            language = "ger"
        elif language == "Englisch":
            language = "eng"
        elif language == "English":
            language = "eng"
        else:
            sys.exit("Unknown language: " + language)
    year = fields[3]
    periodicity = formats[format]["008"]
    f008 = marc_build_field_008(year, periodicity, language)
    marcrecord.add("008", data=f008)

    # Geographical coordinates
    coordinates = fields[8]
    if coordinates:
        coordinates = coordinates.split(";")
        subfields = []
        for coordinate in coordinates:
            directions = coordinate.split(",")
            for direction in directions:
                subfield, value = direction.split(":")
                subfields.append(subfield)
                subfields.append(value)
        marcrecord.add("034", subfields=subfields)

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

    # First creator
    f100a = fields[5]
    marcrecord.add("100", a=f100a)

    # Title statement
    f245a = fields[2]
    marcrecord.add("245", a=f245a)

    # Year of publication
    f260c = fields[3]
    marcrecord.add("260", c=f260c)

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

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

    # Abstract
    f520a = fields[4]
    marcrecord.add("520", a=f520a)

    # Subject headings
    subjects = fields[7]
    if subjects:
        subjects = subjects.split(", ")
        for subject in subjects:
            marcrecord.add("650", a=subject)

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

    # Link to fulltext
    f856u = fields[10]
    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=SID, c="sid-194-col-mining")

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

inputfile.close()
outputfile.close()
