from bs4 import BeautifulSoup
import re


def __getAddresses(parsed: BeautifulSoup) -> list:
    """Function to extract company addresses from the parsed HTML EDGAR page.
    Searches for address information in divs with class name 'mailer'.
    
    Arguments:
        parsed {BeautifulSoup} -- Parsed HTML from company EDGAR filing.
    
    Returns:
        list -- List of addresses.
    """

    # Addresses container
    address_divs = parsed.find_all('div', class_='mailer')

    # Building RegEx for phone number
    # The following RegEx extracts phone numbers in the following formats:
    #   1. (###) ###-####
    #   2. ###-###-####
    #   3. ##########
    phone_number_regex = re.compile(
        r'(\(\d{3}\) \d{3}-\d{4}|\d{3}-\d{3}-\d{4}|\d{10})')

    # List for final addresses
    addresses = list()

    for address in address_divs:
        # Create dict for address
        address_parsed = dict()
        # Split text by newline
        address_items = address.text.split('\n')
        # Removing leading and trailing spaces
        address_items = [i.strip() for i in address_items]

        # Variable to store street address
        street_address = ''

        # Iterate through each line
        for idx, address_item in enumerate(address_items):
            # First line is address type
            if idx == 0:
                address_parsed['type'] = address_item
                continue

            # Check if line has phone number
            phone_matches = phone_number_regex.findall(address_item)
            if len(phone_matches) == 1:
                # Stripping non-digit characters from phone number
                phone_number = re.sub('[^0-9]', '', phone_matches[0])
                address_parsed['phone'] = phone_number
                continue
            
            # If no number, add to address line
            street_address += address_item.strip() + ' '
    
        # Adding street address to parsed address
        address_parsed['street_address'] = street_address.strip()

        # Adding parsed address to addresses master list
        addresses += [address_parsed]

    return addresses