# -*- coding: utf-8 -*-
#
# RERO ILS
# Copyright (C) 2019 RERO
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# This program 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

"""rero-ils UNIMARC model definition."""

import jsonref
from dojson import utils
from dojson.utils import GroupableOrderedDict
from pkg_resources import resource_string

from rero_ils.dojson.utils import ReroIlsUnimarcOverdo, TitlePartList, \
    add_note, build_string_from_subfields, get_field_items, \
    get_field_link_data, make_year, not_repetitive, \
    remove_trailing_punctuation
from rero_ils.modules.documents.api import Document

_ISSUANCE
_MAIN_TYPE_PER_BIB_LEVEL = {
    'a': 'rdami:1001',
    'c': 'rdami:1001',
    'i': 'rdami:1004',
    'm': 'rdami:1001',
    's': 'rdami:1003'
}

_ISSUANCE_SUBTYPE_PER_BIB_LEVEL = {
    'a': 'article',
    'c': 'privateFile',
    'm': 'materialUnit'
}

_ISSUANCE_SUBTYPE_PER_SERIAL_TYPE = {
    'a': 'periodical',
    'b': 'monographicSeries',
    'e': 'updatingLoose-leaf',
    'f': 'updatingWebsite',
    'g': 'updatingWebsite',
   
 'h': 'updatingWebsite'
}

_COUNTRY_UNIMARC_MARC21 = {
    'AD': 'an',
    'AE': 'ts',
    'AF': 'af',
    'AG': 'aq',
    'AI': 'am',
    'AL': 'aa',
    'AM': 'ai',
    'AO': 'ao',
    'AQ': 'ay',
    'AR': 'ag',
    'AS': 'as',
    'AT': 'au',
    'AU': 'at',
    'AUT': 'at',
    'AW': 'aw',
    'AZ': 'aj',
    'BA': 'bn',
    'BB': 'bb',
    'BD': 'bg',
    'BE': 'be',
    'BF': 'uv',
    'BG': 'bu',
    'BH': 'ba',
    'BI': 'bd',
    'BJ': 'dm',
    'BL': 'sc',
    'BM': 'bm',
    'BN': 'bx',
    'BO': 'bo',
    'BR': 'bl',
    'BS': 'bf',
    'BT': 'bt',
    'BV': 'bv',
    'BW': 'bs',
    'BZ': 'bh',
    'CA': 'xxc',
    'CC': 'xb',
    'CD': 'cf',
    'CF': 'cx',
    'CG': 'cg',
    'CH': 'sz',
    'CI': 'iv',
    'CK': 'cw',
    'CL': 'cl',
    'CM': 'cm',
    'CN': 'cc',
    'CO': 'ck',
    'CR': 'cr',
    'CU': 'cu',
    'CW': 'co',
    'CX': 'xa',
    'CY': 'cy',
    'DE': 'gw',
    'DJ': 'ft',
    'DK': 'dk',
    'DM': 'dq',
    'DZ': 'ae',
    'EC': 'ec',
    'EE': 'er',
    'EG': 'ua',
    'EH': 'ss',
    'ER': 'ea',
    'ES': 'sp',
    'ET': 'et',
    'FI': 'fi',
    'FJ': 'fj',
    'FM': 'fm',
    'FO': 'fa',
    'FR': 'fr',
    'GA': 'go',
    'GB': 'xxk',
    'GD': 'gd',
    'GE': 'gau',
    'GF': 'fg',
    'GG': 'gg',
    'GH': 'gh',
    'GI': 'gi',
    'GL': 'gl',
    'GM': 'gm',
    'GN': 'gv',
    'GP': 'gp',
    'GQ': 'eg',
    'GR': 'gr',
    'GS': 'xs',
    'GT': 'gt',
    'GU': 'gu',
    'GW': 'pg',
    'GY': 'gy',
    'HM': 'hm',
    'HN': 'ho',
    'HR': 'ci',
    'HT': 'ht',
    'HU': 'hu',
    'ID': 'io',
    'IE': 'ie',
    'IL': 'is',
    'IM': 'im',
    'IN': 'ii',
    'IQ': 'iq',
    'IR': 'ir',
    'IS': 'ic',
    'IT': 'it',
    'JE': 'je',
    'JM': 'jm',
    'JO': 'jo',
    'JP': 'ja',
    'KE': 'ke',
    'KG': 'kg',
    'KH': 'cb',
    'KI': 'gb',
    'KM': 'cq',
    'KN': 'xd',
    'KP': 'kn',
    'KR': 'ko',
    'KW': 'ku',
    'KY': 'cj',
    'KZ': 'kz',
    'LA': 'ls',
    'LB': 'le',
    'LC': 'xk',
    'LI': 'lh',
    'LK': 'ce',
    'LR': 'lb',
    'LS': 'lo',
    'LT': 'li',
    'LU': 'lu',
    'LV': 'lv',
    'LY': 'ly',
    'MA': 'mr',
    'MC': 'mc',
    'MD': 'mv',
    'ME': 'mo',
    'MG': 'mg',
    'MH': 'xe',
    'MK': 'xn',
    'ML': 'ml',
    'MM': 'br',
    'MN': 'mp',
    'MP': 'nw',
    'MQ': 'mq',
    'MR': 'mu',
    'MS': 'mj',
    'MT': 'mm',
    'MU': 'mf',
    'MV': 'xc',
    'MW': 'mw',
    'MX': 'mx',
    'MY': 'my',
    'MZ': 'mz',
    'NA': 'sx',
    'NC': 'nl',
    'NE': 'ng',
    'NF': 'nx',
    'NG': 'nr',
    'NI': 'nq',
    'NL': 'ne',
    'NO': 'no',
    'NP': 'np',
    'NR': 'nu',
    'NU': 'xh',
    'NZ': 'nz',
    'OM': 'mk',
    'PA': 'pn',
    'PE': 'pe',
    'PF': 'fp',
    'PG': 'pp',
    'PH': 'ph',
    'PK': 'pk',
    'PL': 'pl',
    'PM': 'xl',
    'PN': 'pc',
    'PR': 'pr',
    'PT': 'po',
    'PW': 'pw',
    'PY': 'py',
    'QA': 'qa',
    'RE': 're',
    'RO': 'rm',
    'RU': 'ru',
    'RW': 'rw',
    'SA': 'su',
    'SB': 'bp',
    'SC': 'se',
    'SD': 'sj',
    'SE': 'sw',
    'SG': 'si',
    'SH': 'xj',
    'SI': 'xv',
    'SK': 'xo',
    'SL': 'sl',
    'SM': 'st',
    'SN': 'sg',
    'SO': 'so',
    'SR': 'sr',
    'SS': 'sd',
    'ST': 'sf',
    'SV': 'es',
    'SX': 'sn',
    'SZ': 'sq',
    'TC': 'tc',
    'TD': 'cd',
    'TF': 'fs',
    'TG': 'tg',
    'TH': 'th',
    'TJ': 'ta',
    'TK': 'tl',
    'TL': 'em',
    'TM': 'tk',
    'TN': 'ti',
    'TO': 'to',
    'TR': 'tu',
    'TT': 'tr',
    'TV': 'tv',
    'TZ': 'tz',
    'UA': 'un',
    'UG': 'ug',
    'US': 'xxu',
    'UY': 'uy',
    'UZ': 'uz',
    'VA': 'vc',
    'VC': 'xm',
    'VE': 've',
    'VN': 'vm',
    'VU': 'nn',
    'WF': 'wf',
    'WS': 'ws',
    'XX': 'xx',
    'YE': 'ye',
    'YT': 'ot',
    'ZA': 'sa',
    'ZM': 'za',
    'ZW': 'rh',
}

unimarc = ReroIlsUnimarcOverdo()


@unimarc.over('type_and_issuance', 'leader')
@utils.ignore_value
def unimarc_type_and_issuance(self, key, value):
    """
    Get document type and mode of issuance.

    Books: LDR/6-7: am
    Journals: LDR/6-7: as
    Articles: LDR/6-7: aa + add field 773 (journal title)
    Scores: LDR/6: c|d
    Videos: LDR/6: g + 007/0: m|v
    Sounds: LDR/6: i|j
    E-books (imported from Cantook)
    """
    type = [{"main_type": "docmaintype_other"}]

    if unimarc.admin_meta_data:
        self['adminMetadata'] = unimarc.admin_meta_data

    if unimarc.record_type == 'a':
        if unimarc.bib_level == 'm':
            type = [{
                "main_type": "docmaintype_book",
                "subtype": "docsubtype_other_book"
            }]
        elif unimarc.bib_level == 's':
            type = [{
                "main_type": "docmaintype_serial"
            }]
        elif unimarc.bib_level == 'a':
            type = [{
                "main_type": "docmaintype_article",
            }]
    elif unimarc.record_type in ['c', 'd']:
        type = [{
            "main_type": "docmaintype_score",
            "subtype": "docsubtype_printed_score"
        }]
    elif unimarc.record_type in ['i', 'j']:
        type = [{
            "main_type": "docmaintype_audio",
            "subtype": "docsubtype_music"
        }]
    elif unimarc.record_type == 'g':
        type = [{
            "main_type": "docmaintype_movie_series",
            "subtype": "docsubtype_movie"
        }]
        # Todo 007
    self['type'] = type

    # get the mode of issuance
    self['issuance'] = {}
    main_type = _ISSUANCE_MAIN_TYPE_PER_BIB_LEVEL.get(
        unimarc.bib_level, 'rdami:1001')
    sub_type = 'NOT_DEFINED'
    if unimarc.bib_level in _ISSUANCE_SUBTYPE_PER_BIB_LEVEL:
        sub_type = _ISSUANCE_SUBTYPE_PER_BIB_LEVEL[unimarc.bib_level]
    if unimarc.serial_type in _ISSUANCE_SUBTYPE_PER_SERIAL_TYPE:
        sub_type = _ISSUANCE_SUBTYPE_PER_SERIAL_TYPE[unimarc.serial_type]
    self['issuance'] = dict(main_type=main_type, subtype=sub_type)


@unimarc.over('identifiedBy', '^003')
@utils.ignore_value
def unimarc_bnf_id(self, key, value):
    """Get ID.

    identifier bnfID 003
    """
    identifiers = self.get('identifiedBy', [])
    if value.startswith('http://catalogue.bnf.fr/'):
        identifiers.append({
            "type": "bf:Local",
            "source": "BNF",
            "value":  value.replace('http://catalogue.bnf.fr/', '')
        })
    return identifiers


@unimarc.over('tableOfContents', '^464..')
@utils.for_each_value
@utils.ignore_value
def marc21_to_tableOfContents(self, key, value):
    """Get tableOfContents from repetitive field 464."""
    table_of_contents = build_string_from_subfields(value, 't')
    if table_of_contents:
        self.setdefault('tableOfCont