import re
import logging


def parse_physionet_record(text):
  """Parse the PhysioNet text and get patient_id, record_number, and note."""
  # The format is described at:
  # http://physionet.org/physiotools/deid/doc/DeidUserManual.pdf
  sep = r'\|\|\|\|'
  optional_date = r'(\d\d/\d\d/\d\d\d\d' + sep + r')?'
  pattern = (r'(\n)*START_OF_RECORD=(?P<patient_id>\d+?)' + sep +
             r'(?P<record_number>\d+?)' + sep + optional_date +
             r'\n(?P<text>.*)\n' + sep + r'END_OF_RECORD')
  match = re.match(pattern, text, re.MULTILINE | re.DOTALL)
  if not match:
    logging.error('Failed to parse record: "%s"', text)
    return

  output = {
      'patient_id': int(match.group('patient_id')),
      'record_number': int(match.group('record_number')),
      'note': match.group('text')
  }
  return output