#Аналогично ht_find, ht_delete, ht_list_all (последняя собирает все записи из всех бакетов и сортирует).
from code.LinkedList import *

def create_buckets(size=1000):
    return [None] * size

def hash_function(name, bucket_size):
    hash_value = 0

    for char in name:
        hash_value = (hash_value * 31 + ord(char)) % bucket_size

    return hash_value

def ht_insert(buckets, name, phone):
  #вычисляет индекс, вызывает ll_insert для соответствующего бакета.
    if buckets is None:
        buckets = create_buckets()

    index = hash_function(name, len(buckets))
    buckets[index] = ll_insert(buckets[index], name, phone)

    return buckets

def ht_find(buckets, name):
    if not buckets:
        return None

    index = hash_function(name, len(buckets))
    return ll_find(buckets[index], name)

def ht_delete(buckets, name):
    if not buckets:
        return buckets

    index = hash_function(name, len(buckets))
    buckets[index] = ll_delete(buckets[index], name)

    return buckets

def ht_list_all(buckets):
    if not buckets:
        return []

    records = []

    for bucket in buckets:
        current = bucket

        while current is not None:
            records.append((current['name'], current['phone']))
            current = current['next']

    records.sort(key=lambda x: x[0])

    return records