"""
This file contains the implementation of interactions with the registry
"""

import cms
import transport
import copy
import json

@cms.Plugin(mimetype='application/json',method='GET')
def get (**_args) :
    """
    This function will return the list of labels available
    """
    _data = copy.copy(transport.registry.DATA)
    _context = _args['config']['system']['context']
    _labels = []
    for _key in _data :
        
        if _key not in  ['default','email','version'] :
            _provider = _data[_key]['provider']
            _name = None
            if 'table' in _data[_key] :
                _name = 'table'
            elif 'collection' in _data[_key] :
                _name = 'collection'
            _table = 'NA' if not _name else _data[_key][_name]
            _plugins = [] if 'plugins' not in _data[_key]else _data[_key]['plugins']
            _icon = f'{_context}/api/disk/read?uri=www/html/_assets/images/{_provider}.png'
            _labels.append({"label":_key,"provider":_provider,'table':_table,'icon':_icon})
        else:
            continue
    return _labels

@cms.Plugin(mimetype="application/json",method="GET")
def providers (**_args):
    technologies = []
    transport.supported().apply(lambda row: [technologies.append({"group":row.name,"name":_name}) for _name in row if _name != '' and row.name in ['sql','nosql','warehouse','cloud']],axis=0)
    return technologies
@cms.Plugin(mimetype="text/plain")
def version (**_args) :
    return transport.__edition__+ ' Edition '+transport.__version__
@cms.Plugin(mimetype="application/json",method="POST")
def apply (**_args):
    _request = _args['request']
    _label = _request.json['label']
    _query = _request.json['query']
    _qreader = transport.get.reader(label=_label)
    try:
        if _query.strip()[0] not in ['{','[']:
            _query = _query.replace('%%','%').replace('%','%%')
            _data =  _qreader.apply(_query) #.astype(str).to_dict(orient='split')
        else:
            _data = _qreader.read( **json.loads(_query))
        if _data.shape[0] :
            _data = _data.astype(str).to_dict(orient='split')
            if 'index' in _data:
                del _data['index']

        else:
            _data = []
        _qreader.close()
        return _data
    except Exception as e:        
        raise Exception( str(e))

def set(**_args):
        """
        This function will update the registry  with data for supported technologies
        """
        pass

