import requests
import json


def request_new_tokens(refresh_token, client_id, client_secret, write_out=None):
    """
    Contacts api.amazon.com/auth/o2/token to retrieve new access and refresh tokens

    :param refresh_token: valid refresh_token
    :param client_id: client_id
    :param client_secret: client_secret
    :param write_out: callable taking dict argument matching 'tokens.txt' schema
    :return: access_token, refresh_token
    """
    s = requests.session()
    params_dict = {
        'grant_type': 'refresh_token',
        'refresh_token': refresh_token,
        'client_id': client_id,
        'client_secret': client_secret
    }
    res = s.post('https://api.amazon.com/auth/o2/token', data=params_dict,
                 headers={'Content-Type': 'application/x-www-form-urlencoded'})
    if res.status_code == 200:
        payload = json.loads(res.content.decode())
        if callable(write_out):
            write_out(payload)
        return payload.get('access_token'), payload.get('refresh_token')
    else:
        raise Exception("Failed to request new tokens: {} {}".format(res.status_code, res.content.decode()))