#!/bin/python3

from ansible.module_utils.basic import AnsibleModule
import xmlrpc
from xmlrpc import client as client_rpc

def main():
    module = AnsibleModule(
        argument_spec = dict(
            url          = dict(required=True),
            username     = dict(aliases=['name',], required=True),
            password     = dict(required=False, no_log=True),
            first_name   = dict(required=False),
            last_name    = dict(required=False),
            user_url     = dict(required=False),
            display_name = dict(required=False),
            nickname     = dict(required=False),
            nicename     = dict(required=False),
            bio          = dict(required=False)
        ),
        supports_check_mode=True,
    )

    params = module.params

    server = client_rpc.ServerProxy(
        'http://%s/xmlrpc.php' % params["url"],
        use_datetime=True,
    )

    skip_fields = ['_ansible_check_mode', 'username', 'password', 'name', 'url']
    mappings = {
        "user_url" : "url",
    }

    details = {}

    for k, v in params.items():
        if k in skip_fields:
            continue
        if v:
            if k in mappings:
                k = mappings[k]
            details[k] = v

    existing_users = server.wp.getUsers(1, params['username'], params['password'])
    current_user = None

    for user in existing_users:
        if user['username'] == params['username']:
            current_user = user
            break
    
    is_changed = False
    
    for k, v in details.items():
        if current_user[k] != details[k]:
            current_user[k] = details[k]
            is_changed = True

    if is_changed and not module.check_mode:
        server.wp.editProfile(1, params['username'], params['password'], details)
    
    facts = {
        "wp_existing_users": existing_users,
    }
    module.exit_json(changed=is_changed, user=dict(current_user), ansible_facts=facts)

if __name__ == '__main__':
    main()
