import fmrest

fms = fmrest.Server('https://10.211.55.15',
                    user='admin',
                    password='admin',
                    database='Contacts',
                    layout='Demo',
                    verify_ssl=False
                   )
fms.login()

"""
Explanation: Editing data with python-fmrest
This is a short example on editing records with python-fmrest.
Import, create server and login
End of explanation
"""


record = fms.get_record(44)
record

"""
Explanation: Get a record that we want to edit
End of explanation
"""


record.name

record.drink

"""
Explanation: We fetched our record from the server. Note that the is_dirty flag is set to False as we haven't modified anything yet.
Let's first look at some fields that we can change:
End of explanation
"""


record.drink = "Tomato Juice"

record.is_dirty

"""
Explanation: Let's say, John Doe likes Tomato Juice better:
End of explanation
"""


record['name'] = 'Jane Doe'
fms.edit(record)

"""
Explanation: Changing the field value made the record "dirty". Note, that nothing has changed on the server yet.
Let's change the name as well and then push the modifications to the server.
End of explanation
"""


changed_field_data = {
    'name': 'John Doe',
    'drink': 'Pepsi'
}

fms.edit_record(44, changed_field_data)

"""
Explanation: We passed the record instance to the edit method of the server and with that changed the data on the server. The True return value tells us that everything went fine.
Change a record without fetching it first
If you know what record you want to edit and want to save yourself the request to fetch it from the server, you can just build a dict of field names and values and send them to the server:
End of explanation
"""


changed_field_data = {
    'name': 'John Doe',
    'drink': 'Pepsi'
}

fms.edit_record(44, field_data = changed_field_data, mod_id = 17)

"""
Explanation: Handle conflicts
What happens when someone else modifies the record in the mean time? Sending edits the way we have done it until now will always overwrite the record on the server. If you want to make sure you don't overwrite other user's changes, set the modification id like this:
End of explanation
"""


from fmrest.exceptions import FileMakerError

record['name'] = 'Jane Doe'
try:
    fms.edit(record, validate_mod_id=True)
except FileMakerError as ex:
    print(ex)

"""
Explanation: In the case of working with the record instance (as in the first example), just pass a boolean flag if you want validation or not (the record instance already knows the modification id from the time of requesting it from the server).
As we changed the record before, let's see what happens:
End of explanation
"""


