#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright 2015-2016 Mir Calculate. http://www.calculate-linux.org
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import argparse
import sys
import re


class ArgumentParserVariable(argparse.ArgumentParser):
    def __init__(self):
        super().__init__(
            description="Fast variable getter")
        group = self.add_mutually_exclusive_group(required=True)
        group.add_argument('--value', nargs="+",
                           help='full variable name')
        group.add_argument('--list', action="store_true",
                           help='variables listing')


def display_variables(variables):
    """
    Display variables by serialize
    """
    from calculate.lib.datavars import DataVars

    dv = DataVars()
    dv.importVariables()
    dv.flIniFile()

    re_index = re.compile("^([\w.]+)(?:\[(-?\d+)\])?$")
    remove_quotes = lambda x: x if x != "''" else ""
    for variable in variables:
        try:
            m = re_index.search(variable)
            if not m:
                raise Exception("wrong variable name %s" % variable)
            varname, index = m.groups()
            value = dv.Get(varname)
            vartype = dv.getInfo(varname).type
            if "list" in vartype and index is not None:
                try:
                    print(remove_quotes(value[int(index)]))
                except (IndexError, AttributeError, ValueError):
                    print("")
            elif index is not None:
                raise Exception("variable %s is not list" % varname)
            else:
                print(remove_quotes(dv.serialize(vartype, value)))
        except Exception as e:
            sys.stderr.write("error: %s\n" % str(e))
            sys.exit(1)


def list_variables():
    """
    List variables
    """
    from calculate.lib.datavars import DataVars

    dv = DataVars()
    dv.importVariables()
    dv.flIniFile()
    for wsdl in dv.Get('main.cl_wsdl_available'):
        dv.importVariables("%s.variables" % wsdl.replace('-', '.'))
    for k, v in sorted(dv.allVars.items(), key=lambda x: (x[1][0], x[0])):
        print("%s.%s" % (v[0], k))


if __name__ == '__main__':
    apv = ArgumentParserVariable()
    args = apv.parse_args()
    if args.list:
        list_variables()
    else:
        display_variables(args.value)
