import json
from copy import deepcopy

def getLayerClassTypeOrder10_v2(order10layer, complexTypesIn, simpleTypesIn):
        if order10layer.type() != 0:
            return ''
        complexTypes = deepcopy(complexTypesIn)
        simpleTypes = deepcopy(simpleTypesIn)

        allOrder10Attributes = set()
        matchesClasses = {'byAllFieldsNames':set(), 'byCLASSID':set(), 'byLayerName':set(), 'nameClassType':'', 'allClassMatches':set()}

        for className, classParameters in complexTypes.items():
            allOrder10Attributes.update(classParameters['attributes'].keys())
            matchesClasses['allClassMatches'].add(className)
        
        fieldsForCheckSet = set(order10layer.fields().names()).intersection(allOrder10Attributes)
        
        #byAllFieldsNames
        classTypes = []
        fieldCount = 0
        for classType in complexTypes.keys():
            if classType in ['date_t', 'Zone', 'Object']:
                continue
            etalonFieldsSet = set(list(complexTypes[classType]['attributes'].keys()))
            commonFields = etalonFieldsSet.intersection(fieldsForCheckSet)
            if len(commonFields) < 2:
                continue
            if len(commonFields) == fieldCount:
                classTypes.append(classType)
            if len(commonFields) > fieldCount:
                fieldCount = len(commonFields)
                classTypes = [classType,]
        matchesClasses['byAllFieldsNames'] = set(classTypes)
        classTypes = []
        fieldCount = 0
        #byCLASSID
        if order10layer.featureCount() > 0 and 'CLASSID' in fieldsForCheckSet:
            indxFieldClassid = order10layer.fields().indexOf('CLASSID')
            setOfCLASSID = order10layer.uniqueValues(indxFieldClassid)
            for classType in complexTypes.keys():
                if classType in ['date_t', 'Zone', 'Object'] or complexTypes[classType]['attributes'].get('CLASSID', {"baseType":'error'})["baseType"] == 'error':
                    continue
                simpleName = complexTypes[classType]['attributes']['CLASSID']['baseType'].replace('fgistp:', '')
                etalonCLASSID = set(list(simpleTypes[simpleName]['dictValues'].keys()))
                if {str(x) for x in setOfCLASSID}.issubset({str(y) for y in etalonCLASSID}):
                    matchesClasses['byCLASSID'].add(classType)
        #byLayerName
        for classType in complexTypes.keys():
            className = classType.replace('_Type', '').lower()
            if className == order10layer.name().lower():
                matchesClasses['byLayerName'] = {classType}
                break
            if className in order10layer.name().lower():
                matchesClasses['byLayerName'].add(classType)
        #result
        if len(matchesClasses['byLayerName'].intersection(matchesClasses['byAllFieldsNames'], matchesClasses['byCLASSID'])) == 1:
            matchesClasses['nameClassType'] = list(matchesClasses['byLayerName'].intersection(matchesClasses['byAllFieldsNames'], matchesClasses['byCLASSID']))[0]
        elif len(matchesClasses['byLayerName'].intersection(matchesClasses['byAllFieldsNames'])) == 1:
            matchesClasses['nameClassType'] = list(matchesClasses['byLayerName'].intersection(matchesClasses['byAllFieldsNames']))[0]
        elif len(matchesClasses['byCLASSID'].intersection(matchesClasses['byAllFieldsNames'])) == 1:
            matchesClasses['nameClassType'] = list(matchesClasses['byCLASSID'].intersection(matchesClasses['byAllFieldsNames']))[0]
        elif len(matchesClasses['byAllFieldsNames']) == 1:
            matchesClasses['nameClassType'] = list(matchesClasses['byAllFieldsNames'])[0]
        else:
            if len(matchesClasses['byLayerName'].union(matchesClasses['byAllFieldsNames'], matchesClasses['byCLASSID'])) > 0:
                matchesClasses['allClassMatches'] = matchesClasses['byLayerName'].union(matchesClasses['byAllFieldsNames'], matchesClasses['byCLASSID'])
        
        
        """ classTypesPartFields = {x + '_Type' for x in self.groupDict.keys()}
        for fieldForCheck in fieldsForCheckSet:
            classesForField = set()
            for classType in complexTypes.keys():
                if classType in ['date_t', 'Zone', 'Object']:
                    continue
                etalonFieldsSet = set(list(complexTypes[classType]['attributes'].keys()))
                if fieldForCheck in etalonFieldsSet:
                    classesForField.add(classType)
            if len(classesForField) > 0:
                classTypesPartFields = classTypesPartFields.intersection(classesForField)
        if len(classTypesPartFields) > 0:
            matchesClasses['byPartFields'] = classTypesPartFields
        if matchesClasses['nameClassType'] == '' and len(classTypesPartFields) == 1:
            matchesClasses['nameClassType'] =list(matchesClasses['byPartFields'])[0]"""
        

        """ my_layer_meta = order10layer.metadata()
        my_layer_meta.setAbstract(str(matchesClasses))

        order10layer.setMetadata(my_layer_meta) """

        return matchesClasses