import re
import logging


def extract_state(resume_segments):
    """
       Find first text which matches one of the states in the string_to_search
       :param resume_segments: Dictionary containing segmented resume data
       :type resume_segments: Dictionary
       :return: state code
       :rtype: str
    """
    try:
        string_to_search = resume_segments['contact_info']
        states = ['AK', 'AL', 'AR', 'AZ', 'CA', 'CO', 'CT', 'DC', 'DE', 'FL', 'GA', 'HI', 'IA', 'ID',
                  'IL', 'IN', 'KS', 'KY', 'LA', 'MA', 'MD', 'ME', 'MI', 'MN', 'MO', 'MS', 'MT', 'NC', 'ND', 'NE',
                  'NH', 'NJ', 'NM', 'NV', 'NY', 'OH', 'OK', 'OR', 'PA', 'PR', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT',
                  'VA', 'VT', 'WA', 'WI', 'WV', 'WY']
        state_pattern = re.compile(r'\b(' + '|'.join(states) + r')\b')
        for line in string_to_search:
            result = state_pattern.search(line)
            if result:
               return result.group()

        return None
    except Exception as e:
        logging.error('Issue parsing state:: ' + str(e))
        return None