#!/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: Medienobservationen
SID: 196
Ticket: #17849, #17853
Origin: SRU

"""


import os
import sys
import re

import marcx
import pymarc
from siskin.configuration import Config
from siskin.utils import marc_clean_record, convert_to_finc_id
from siskin.arguments import FincArgumentParser


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

SID = "196"

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)

# 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)
    os.system('srufetch -e https://services.dnb.de/sru/dnb -m 30 -q "partOfat=019676700" -a MARC21-xml -xr "(?ms)(<record xmlns(.*?)</record>)" > %s' % inputfile)

inputfile = open(inputfile, "rb")
reader = pymarc.marcxml.parse_xml_to_array(inputfile)


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

for record in reader:

    record = marcx.Record.from_record(record)
    record.force_utf8 = True
    record.strict = False

    # Identifikator
    f001 = record["001"].data
    record.remove_fields("001")
    record.add("001", data="196-" + f001)

    # Put date into field 260c
    f773g = record["773"]["g"]
    match = re.search("(\d\d\d\d)", f773g)
    if match:
        f260c = match.group(1)
        record.add("260", c=f260c)

    # Only use 773t and 773x and kick the rest.
    record.remove_fields("773")
    record.add("773", t="Medienobservationen", x="1612-7315")

    # Kollektion
    record.add("980", a=f001, b=SID, c="sid-196-col-obs")

    # Convert all identifier in 001, 770, 772 ... to Finc schema
    record = convert_to_finc_id(SID, record, encode=False, finc_prefix=False)

    # Remove empty subfields
    marc_clean_record(record)

    if outputformat == "xml":
        outputfile.write(record)
    else:
        outputfile.write(record.as_marc())

inputfile.close()
outputfile.close()
