module Canql

grammar Patient
  rule gender
    space gender:('male' / 'female') word_break <Nodes::Patient::GenderNode>
  end

  rule outcome
    space outcome:('stillborn' / 'liveborn' / 'miscarried' / 'terminated' / 'registrable' / 'non-registrable' ) word_break <Nodes::Patient::OutcomeNode>
  end

  rule primacy
    space primacy:('primary' / 'alias' ) word_break <Nodes::Patient::PrimacyNode>
  end

  rule category
    space category:('eurocat amber and green' /
      'eurocat red and amber' / 'eurocat red' / 'eurocat amber' /
      'eurocat green' / 'eurocat' /
      'fasp red and amber' / 'fasp amber and red' / 'fasp red' /
      'fasp amber' / 'fasp green' / 'fasp excluded'
    ) word_break <Nodes::Patient::CategoryNode>
  end

  rule expected_keyword
    space ('expected' / 'due') word_break
  end

  rule expected
    expected_keyword fuzzy_date <Nodes::Patient::ExpectedDateRangeNode>
  end

  rule case_field_existance
    and_keyword? field_existance_modifier:existance_keyword patient_field_list:case_field_list  <Nodes::Patient::FieldExists>
  end

  rule patient_field_existance
    and_keyword? field_existance_modifier:existance_keyword patient_field_list:patient_field_list  <Nodes::Patient::FieldExists>
  end

  rule patient_fields_keyword
    space 'field' 's'? word_break
  end

  rule case_field_list
    space case_field_names (comma case_field_names)*
  end

  rule patient_field_list
    space patient_field_names (comma patient_field_names)*
  end

  rule case_field_names
    patient_field_name:(
      'date of birth' / 'dob' / 'date of vital status' / 'nhs number' /
      'delivery postcode' / 'booking postcode' / 'birth weight' /
      'place of delivery' / 'sex' / 'outcome' / 'edd' /
      'expected delivery date' / 'booking hospital' / 'screening status' /
      'number of fetuses at delivery' / 'malformed in set' / 'gestation at delivery' /
      'booking date'
    )
  end

  rule patient_field_names
    patient_field_name:(
      'date of birth' / 'dob' / 'date of vital status' / 'nhs number' / 'sex'
    )
  end

  rule mother_conditions
    and_keyword? space subject:'mother' word_break mother_additional_conditions mother_with_clause?
  end

  rule mother_additional_conditions
    mother_age_conditions*
  end

  rule mother_age_conditions
    and_keyword? (with_birth_date / with_death_date)
  end

  rule mother_with_clause
    with_keyword? post:mother_with_conditions+
  end

  rule mother_with_conditions
    patient_field_existance / action_or_ebr
  end
end

end