def get_team_attr_rankings_page(global_config, comp, attr_name):
        
    global_config['logger'].debug( 'GET Team Attribute Rankings' )
    
    session = DbSession.open_db_session(global_config['db_name'])
        
    attrdef_filename = './config/' + global_config['attr_definitions']
    attr_definitions = AttributeDefinitions.AttrDefinitions()
    attr_definitions.parse(attrdef_filename)
    attr = attr_definitions.get_definition(attr_name)
    try:
        stat_type = attr['Statistic_Type']
    except:
        stat_type = 'Total'

    web.header('Content-Type', 'application/json')
    result = []
    result.append('{ "rankings": [\n')
            
    team_rankings = DataModel.getTeamAttributesInRankOrder(session, comp, attr_name, False)
    for team in team_rankings:
        if stat_type == 'Average':
            value = int(team.cumulative_value/team.num_occurs)
        else:
            value = int(team.cumulative_value)
        data_str = '{ "team": %d, "value": %d }' % (team.team,value)
        result.append(data_str)
        result.append(',\n')
    if len(team_rankings) > 0:
        result = result[:-1]
        result.append('\n')
    result.append(']}')
    return ''.join(result)
def get_team_attr_rankings_json(global_config, comp=None, attr_name=None):
        
    global_config['logger'].debug( 'GET Team Attribute Rankings Json' )
    store_data_to_file = False
    
    if comp == None:
        comp = global_config['this_competition'] + global_config['this_season']
        season = global_config['this_season']
    else:
        season = WebCommonUtils.map_comp_to_season(comp)

    session = DbSession.open_db_session(global_config['db_name'] + season)

    attrdef_filename = WebCommonUtils.get_attrdef_filename(comp=comp)
    attr_definitions = AttributeDefinitions.AttrDefinitions()
    attr_definitions.parse(attrdef_filename)
    attr_def = attr_definitions.get_definition(attr_name)
    try:
        stat_type = attr_def['Statistic_Type']
    except:
        stat_type = 'Total'
        
    web.header('Content-Type', 'application/json')
    result = []
    result.append('{  "attr_name" : "%s",\n' % attr_name)
    
    # add the columns bases on the attribute definition type
    result.append('   "columns" : [\n')
    result.append('      { "sTitle": "Team" }')
    result.append(',\n')
    columns = []
    if attr_def['Type'] == 'Map_Integer':
        map_values = attr_def['Map_Values'].split(':')
        for map_value in map_values:
            item_name = map_value.split('=')[0]
            columns.append(item_name)
            result.append('      { "sTitle": "%s" }' % item_name)
            result.append(',\n')
        result = result[:-1]
        result.append('\n')
        result.append('   ],\n')

    if stat_type == 'Average':
        team_rankings = DataModel.getTeamAttributesInAverageRankOrder(session, comp, attr_name)        
    else:
        team_rankings = DataModel.getTeamAttributesInRankOrder(session, comp, attr_name)

    result.append('   "rankings" : [\n')
    for team_attr in team_rankings:
        data_str = '      [ %d,' % team_attr.team
        value_dict = DataModel.mapAllValuesToDict(attr_def, team_attr.all_values)
        for column in columns:
            try:
                value = value_dict[column]
            except:
                value = 0
            data_str += ' %d,' % value
        data_str = data_str.rstrip(',')
        data_str += ' ]'
        result.append(data_str)
        result.append(',\n')

    if len(team_rankings) > 0:
        result = result[:-1]
    result.append('\n')
    result.append('   ]\n}')    
    
    json_str = ''.join(result)
    
    if store_data_to_file is True:
        try:
            file_name = 'attrrankings_%s' % attr_name
            FileSync.put( global_config, '%s/EventData/%s.json' % (comp,file_name), 'text', json_str)
        except:
            raise
        
    session.remove()
    return json_str
def get_team_rankings_json(global_config, season, event, attr_filters=[], filter_name=None, 
                           thumbnails = False, store_json_file=False):
        
    global_config['logger'].debug( 'GET Team Rankings Json' )
    store_data_to_file = False
    
    comp = WebCommonUtils.map_event_code_to_comp(event, season)

    session = DbSession.open_db_session(global_config['db_name'] + season)

    result = []
    result.append('{ "rankings": [\n')
    rank_added = False
    
    if len(attr_filters) == 0:
        team_rankings = DataModel.getTeamsInRankOrder(session, comp, False)
        for team in team_rankings:
            # round the score to an integer value
            team.score = float(int(team.score))
            if team.score > 0:
                thumbnails_snippet = ''
                if thumbnails:
                    thumbnails_snippet = ',\n' + get_team_scouting_thumbnails_json_snippet(global_config, comp, str(team.team))
                
                result.append( '  { "score": %0.1f, "competition": "%s", "team": %d%s }' % (team.score, comp, team.team,thumbnails_snippet))
                result.append(',\n')
                rank_added = True
    else:
        # we'll need the attribute definitions in order to retrieve the correct attribute value
        # and attribute weighting
        attrdef_filename = WebCommonUtils.get_attrdef_filename(comp=comp)
        attr_definitions = AttributeDefinitions.AttrDefinitions(global_config)
        attr_definitions.parse(attrdef_filename)
        
        team_rank_dict = dict()
        for attr_filter in attr_filters:
            try:
                attr_name, attr_value = attr_filter.split('=')
            except:
                attr_name = attr_filter
                attr_value = None
            
            attr_def = attr_definitions.get_definition(attr_name)
            
            if attr_value is None:
                team_rankings = DataModel.getTeamAttributesInRankOrder(session, comp, attr_name, False)
                
                for team in team_rankings:
                    try:
                        stat_type = attr_def['Statistic_Type']
                    except:
                        stat_type = 'Total'
        
                    weight = int(float(attr_def['Weight']))
                    if stat_type == 'Average':
                        score = int(team.cumulative_value/team.num_occurs*weight)
                    else:
                        score = int(team.cumulative_value*weight)
                                                    
                    try:       
                        team_rank_dict[team.team] += score
                    except:
                        team_rank_dict[team.team] = score
            else:
                team_rankings = DataModel.getTeamAttributesWithValue(session, comp, attr_name, attr_value, False)
                
                for team in team_rankings:
                    score = team.all_values.count(attr_value)
                    try:       
                        team_rank_dict[team.team] += score
                    except:
                        team_rank_dict[team.team] = score
                
                    
        sorted_team_rank = sorted(team_rank_dict.items(), key=operator.itemgetter(1))
        for team, score in sorted_team_rank:
            # round the score to an integer value
            score = float(int(score))
            if score > 0:
                thumbnails_snippet = ''
                if thumbnails:
                    thumbnails_snippet = ',\n' + get_team_scouting_thumbnails_json_snippet(global_config, comp, str(team))
                
                result.append( '  { "score": %0.1f, "competition": "%s", "team": %d%s }' % (score, comp, team, thumbnails_snippet))
                result.append(',\n')
                rank_added = True
        
    if rank_added == True:
        result = result[:-1]

    result.append(']}')
    
    json_str = ''.join(result)
    
    if store_json_file is True:
        try:
            if filter_name is None:
                file_name = 'scoutingrankings'
            else:
                file_name = 'scoutingrankings_%s' % filter_name
            FileSync.put( global_config, '%s/EventData/%s.json' % (comp,file_name), 'text', json_str)
        except:
            raise
        
    session.remove()
    return json_str