"""
Build 'use others module data' mechanism for f2py2e.

Copyright 1999 -- 2011 Pearu Peterson all rights reserved.
Copyright 2011 -- present NumPy Developers.
Permission to use, modify, and distribute this software is given under the
terms of the NumPy License.

NO WARRANTY IS EXPRESSED OR IMPLIED.  USE AT YOUR OWN RISK.
"""
__version__ = "$Revision: 1.3 $"[10:-1]

f2py_version = 'See `f2py -v`'


from .auxfuncs import applyrules, dictappend, gentitle, hasnote, outmess

usemodule_rules = {
    'body': """
#begintitle#
static char doc_#apiname#[] = \"\\\nVariable wrapper signature:\\n\\
\t #name# = get_#name#()\\n\\
Arguments:\\n\\
#docstr#\";
extern F_MODFUNC(#usemodulename#,#USEMODULENAME#,#realname#,#REALNAME#);
static PyObject *#apiname#(PyObject *capi_self, PyObject *capi_args) {
/*#decl#*/
\tif (!PyArg_ParseTuple(capi_args, \"\")) goto capi_fail;
printf(\"c: %d\\n\",F_MODFUNC(#usemodulename#,#USEMODULENAME#,#realname#,#REALNAME#));
\treturn Py_BuildValue(\"\");
capi_fail:
\treturn NULL;
}
""",
    'method': '\t{\"get_#name#\",#apiname#,METH_VARARGS|METH_KEYWORDS,doc_#apiname#},',
    'need': ['F_MODFUNC']
}

################


def buildusevars(m, r):
    ret = {}
    outmess(
        f"\t\tBuilding use variable hooks for module \"{m['name']}\" (feature only for F90/F95)...\n")
    varsmap = {}
    revmap = {}
    if 'map' in r:
        for k in r['map'].keys():
            mapped_name = r['map'][k]
            if mapped_name in revmap:
                outmess(f'\t\t\tVariable "{mapped_name}<={k}" is already mapped by '
                        f'"{revmap[mapped_name]}". Skipping.\n')
            else:
                revmap[mapped_name] = k
    if r.get('only'):
        for v in r['map'].keys():
            if r['map'][v] in m['vars']:

                if revmap[r['map'][v]] == v:
                    varsmap[v] = r['map'][v]
                else:
                    outmess(f"\t\t\tIgnoring map \"{v}=>{r['map'][v]}\". See above.\n")
            else:
                outmess(
                    f"\t\t\tNo definition for variable \"{v}=>{r['map'][v]}\". Skipping.\n")
    else:
        for v in m['vars'].keys():
            varsmap[v] = revmap.get(v, v)
    for v in varsmap.keys():
        ret = dictappend(ret, buildusevar(v, varsmap[v], m['vars'], m['name']))
    return ret


def buildusevar(name, realname, vars, usemodulename):
    outmess('\t\t\tConstructing wrapper function for variable '
            f'"{name}=>{realname}"...\n')
    ret = {}
    vrd = {'name': name,
           'realname': realname,
           'REALNAME': realname.upper(),
           'usemodulename': usemodulename,
           'USEMODULENAME': usemodulename.upper(),
           'texname': name.replace('_', '\\_'),
           'begintitle': gentitle(f'{name}=>{realname}'),
           'endtitle': gentitle(f'end of {name}=>{realname}'),
           'apiname': f'#modulename#_use_{realname}_from_{usemodulename}'
           }
    nummap = {0: 'Ro', 1: 'Ri', 2: 'Rii', 3: 'Riii', 4: 'Riv',
              5: 'Rv', 6: 'Rvi', 7: 'Rvii', 8: 'Rviii', 9: 'Rix'}
    vrd['texnamename'] = name
    for i in nummap.keys():
        vrd['texnamename'] = vrd['texnamename'].replace(repr(i), nummap[i])
    if hasnote(vars[realname]):
        vrd['note'] = vars[realname]['note']
    rd = dictappend({}, vrd)

    print(name, realname, vars[realname])
    ret = applyrules(usemodule_rules, rd)
    return ret
