import addressbook_pb2

if __name__ == '__main__':

    # Create a person.
    person = addressbook_pb2.Person()
    print(person)

    # Specify the information of that person.
    person.name = "Alice"
    person.id = 1
    person.email = "alice@email.com"

    phone_number = person.phones.add()
    phone_number.number = "1234567"
    phone_number.type = addressbook_pb2.Person.PhoneType.MOBILE

    # Trying to set a field that does not exist will raise an error.
    # person.age = 23

    # Trying to set a field to a value of the wrong type will raise an error.
    # person.name = 10

    print(person)

    # Serialize to string.
    person_str = person.SerializeToString()

    print("String:", person_str)

    # Save to file.
    with open("output", "wb") as f:
        f.write(person.SerializeToString())

    # Read from file.
    person_new = addressbook_pb2.Person()
    with open("output", "rb") as f:
        person_new.ParseFromString(f.read())

    print(person_new)