import pymysql

#---DATABASE_CONNECTION---
try:
    connection = pymysql.connect(
        host='localhost',
        user='root',
        password='password',
        database='ovpn',
        cursorclass=pymysql.cursors.DictCursor
    )
    print("Connected to MySQL database")
except Exception as e:
    print(e)
    
num_projects = 3
server_list = []

# projects = [
#     {"project1": "1134"},
#     {"project2": "1120"},
#     {"project3": "1134"},
# ]
projects = {"project1": "1134","project2": "1120","project3": "1134"}

len_project = len(projects)


def insert_project_serverData(country_list):
    for country in country_list:
        country_id, db_offset, db_limit = country['country_id'], country['db_offset'], country['db_limit']
        project_number = country['project_no']

        # cursor = connection.cursor()
        # cursor.execute("SELECT * from ovpn_servers_new ")
        # get_server = 


#--------MAIN_FUNTION---------
def main():
    # try:
        cursor = connection.cursor()
        cursor.execute("""SELECT *
                    FROM (
                        SELECT *,
                            ROW_NUMBER() OVER (PARTITION BY country_id ORDER BY updated_at DESC) AS row_num
                        FROM ovpn_servers_new
                        WHERE is_active = 1
                        
                    ) AS numbered_rows
                    WHERE row_num <= 5
                    ORDER BY country_id ASC, row_num ASC""")

        total_active_servers = cursor.fetchall()

        print('============',total_active_servers[0])
        country_dict = {}

        # Iterate through query results and populate the country_dict
        for row in total_active_servers:
            country_id = row['country_id']
            if country_id not in country_dict:
                country_dict[country_id] = []
            
            country_dict[country_id].append({
                'server_id': row['server_id'],
                'updated_at': row['updated_at'],
                # ... add more fields as needed ...
            })
        

        divided_country_data = {}

        for country_id, servers in country_dict.items():
                total_servers = len(servers)
                parts = num_projects  # Use the variable for the number of projects

                # Calculate the number of servers per part
                servers_per_part = total_servers // parts

                # Initialize the starting index
                start_index = 0

                # Divide servers into equal parts using modulo method

                print(len_project)
                for part_number in range(len_project):
                    # print(part_number)
                    # print(part_number[''])
                    end_index = start_index + servers_per_part + (1 if len_project <= total_servers % parts else 0)
                    project_name = f"project{part_number}"

                    print('======project_name', project_name)
                    if project_name in projects:
                        print('-----', project_name)
                        value = projects[project_name]  
                        print('===============', value)
                        divided_country_data.setdefault(country_id, {})[value] = servers[start_index:end_index]
                    else:
                        print('===========')
                    
                    start_index = end_index

        print(divided_country_data)
    
        if server_list != []:
            server_data = insert_project_serverData(server_list)

    # except Exception as e:
    #     print(e)

if __name__ == '__main__':
    main()