#! /usr/bin/env python
# ===================================================================
# file:   testscan.py
# author: k.koepernik@ifw-dresden.de
# date:   04 Okt 2018

from __future__ import print_function
import pyfplo.fploio as fploio
import argparse
import json

version = 20181002

parser = argparse.ArgumentParser(description='Translates `=.*` files \
                                 (e.g., `=.in`, `=.xef`, `=.dens`) into \
                                 a JSON file without calling pyfplo. \
                                 Works with Python 2, but the order \
                                 of entries is retained in Python 3, \
                                 only.', conflict_handler='resolve',
                                 epilog="Please report any bugs to \
                                 Oleg Janson <olegjanson@gmail.com>.")
parser.add_argument('-i', '--input', default='=.in',
                    type=str,dest='input',
                    help='FPLO input file (default:%(default)s)')
parser.add_argument('-o', '--output', type=argparse.FileType('w'),
                    default='-', help='JSON output file')
parser.add_argument('-n', '--nice', dest='nice', action='store_true',
                    help='add indents (otherwise just a single line)')
parser.set_defaults(nice=False)
parser.add_argument('-v', '--version', action='version',\
                     help='print the version',\
                     version='%(prog)s version {:d}'.format(version))
args = parser.parse_args()
jsonprintoptions = ({}, {'indent':4})[args.nice]

# ===================================================================
# 
# ===================================================================
def scanStruct(d,dictdata,ind=''):
    n=d.first()
    while True:
        if n.isScalar():
            if n.isInt():
                dictdata[n.name()]=n.L
            elif n.isReal():
                dictdata[n.name()]=n.D
            elif n.isLogical():
                dictdata[n.name()]=bool(n.L)
            elif n.isFlag():
                dictdata[n.name()]=bool(n.L)
            else:
                dictdata[n.name()]=n.S
        elif n.isArray():
            dictdata[n.name()]=[]
            scanArray(n,dictdata[n.name()],n.sizes(),len(n.sizes()))
        elif n.isStruct():
            dictdata[n.name()]={}
            scanStruct(n,dictdata[n.name()],ind+'    ')
        elif n.isStructArray():
            dictdata[n.name()]=[]
            for i in range(n.size()):
                dictdata[n.name()].append({})
                scanStruct(n[i],dictdata[n.name()][-1],ind+'    ')
            

        if not n.hasNext(): break
        n=n.next()
    
    return
# ===================================================================
# 
# ===================================================================
def scanArray(d,dictdata,sizes,dim,idx=[],ind=''):

    if dim==len(sizes):
        idx=[0]*dim
    for i in range(sizes[dim-1]):
        idx[dim-1]=i
        if dim==1:
            n=d[tuple(idx)]
            if n.isInt():
                dictdata.append(n.L)
            elif n.isReal():
                dictdata.append(n.D)
            elif n.isLogical():
                dictdata.append(bool(n.L))
            elif n.isFlag():
                dictdata.append({n.S[0:-3]:bool(n.L)})
            else:
                dictdata.append(n.S)
        else:
            dictdata.append([])
            scanArray(d,dictdata[-1],sizes,dim-1,idx,ind='')
    
    return

# ===================================================================
# 
# ===================================================================

if __name__ == '__main__':

    p=fploio.INParser()
    p.parseFile(args.input)

    dictdata={}
    scanStruct(p(),dictdata)


    with args.output as jsonfile:
        json.dump(dictdata, jsonfile, **jsonprintoptions)
    





