#!/usr/bin/env python3


# Python program to read
# json file
  
  
import json
from itertools import groupby
  




#good_domains = json.load(open('good.json'))
#bad_domains = json.load(open("bad.json"))

  



def get_top_registrars(registrars: list, top: int = 0) -> list:
    """Returns the top registrars by number of domains"""
    if top == 0:
        return sorted(registrars, key=lambda x: x['count'], reverse=True)
    else:
        return sorted(registrars, key=lambda x: x['count'], reverse=True)[:top]




def sort_registrars(domains):   
    """Returns a list of registrars and their domain counts"""
    
    registrar_list = []

    for domain in domains:

        registrar = None
        try:
            registrar = domain['whois_data']['registrar']
        except Exception as e: 
            #print("No whois data")
            pass

        if registrar is not None:
            registrar_list.append(registrar)
            
            
    registrars_sorted = []
    for value, repeated in groupby(sorted(registrar_list)):
        reg = {"registrar": value, "count": sum(1 for _ in repeated)}
        registrars_sorted.append(reg)
        
    return registrars_sorted

 
def load_json(path):
    with open(path) as f:
        return json.load(f)
    
def get_registrars(collection, top_registrars: int = 0):
    domains = json.load(open(collection))
    
    sorted = sort_registrars(domains)
    return get_top_registrars(sorted, top_registrars)


def save_json(path, data):
    with open(path, "w") as f:
        json.dump(data, f, indent=4, sort_keys=True, default=str)
        
    


if __name__ == "__main__":
    good_reg_dict = get_registrars("/home/poli/Desktop/domain-data-master/good.json")
    bad_reg_dict  = get_registrars("/home/poli/Desktop/domain-data-master/bad.json")
    
    save_json("good_registrars.json", good_reg_dict)
    save_json("bad_registrars.json", bad_reg_dict)
    
    

