# (c) cavaliba.com - related.py

import json
import yaml 

from app_data.models import DataEAV
from app_data.schema import Schema






def get_unwanted_schemanames():

    # NEXT : create schema option / configuration
    return ['sirene_message']




def is_authorized_schema(schemaname=None, aaa=None):
    '''
    True/False if aaa can read schema's Objects
    '''

    if not aaa:
        return True
    
    schema = Schema.from_name(schemaname)
    if schema:
        if schema.has_read_permission(aaa=aaa):
            return True
    
    return False




def get_related(classname=None, keyname=None, aaa=None):
    '''
    IN:

    OUT: dict[schemaname] =  {
            displayname: XXXX
            count: ###
            instances:
            - EAVInstance {}
            - EAVInstance {}
            - ...
            }
    if aaa provided, reply is filtered with aaa read permission
    on each schema's instances.

    '''

    reply = {}
    
    if not classname:
        return reply 
    
    if not keyname:
        return reply 


    instances_eav =  DataEAV.objects.filter(
        format = 'schema:' + classname,
        value = keyname
    )

    # prepare struct
    
    # dict of all classname => displayname
    classname2displayname = Schema.displayname_dict()
    
    unwanted_schemanames = get_unwanted_schemanames()


    for schemaname, displayname in classname2displayname.items():

        # filter unwanted Schema for related
        if schemaname in unwanted_schemanames:
            continue

        if not is_authorized_schema(schemaname=schemaname, aaa=aaa):
            continue

        reply[schemaname] = {}
        reply[schemaname]['displayname'] = displayname
        reply[schemaname]['count'] = 0
        reply[schemaname]['instances'] = []
    
    # Loop on instances from EAV
    for i in instances_eav:
        if i.classname in reply:
            reply[i.classname]['count'] += 1
            reply[i.classname]['instances'].append(i)
            

    return reply