const randomBytes = require('crypto').randomBytes;

const AWS = require('aws-sdk');

const ddb = new AWS.DynamoDB.DocumentClient();

const fleet = [
    {
        Name: 'Arthur',
        Gender: 'Llama blanc'
    },
    {
        Name: 'Perceval',
        Gender: 'Alpaga'
    },
    {
        Name: 'Karadoc',
        Gender: 'Guanaco'
    },
];

exports.handler = (event, context, callback) => {
    if (!event.requestContext.authorizer) {
      errorResponse('Authorization not configured', context.awsRequestId, callback);
      return;
    }

    const runId = toUrlString(randomBytes(16));
    console.log('Received event (', runId, '): ', event);
    
    const username = event.requestContext.authorizer.claims['cognito:username'];
    const requestBody = JSON.parse(event.body);
    const pickupLocation = requestBody.PickupLocation;
    const llama = findLlama(pickupLocation);

    recordRun(runId, username, llama).then(() => {
        callback(null, {
            statusCode: 201,
            body: JSON.stringify({
                runId: runId,
                llama: llama,
                llamaName: llama.Name,
                Eta: '30 seconds',
                runr: username
            }),
            headers: {
                'Access-Control-Allow-Origin': '*',
            },
        });
    }).catch((err) => {
        console.error(err);
        errorResponse(err.message, context.awsRequestId, callback)
    });
};

function findLlama(pickupLocation) {
    console.log('Finding llama for ', pickupLocation.Latitude, ', ', pickupLocation.Longitude);
    return fleet[Math.floor(Math.random() * fleet.length)];
}

function recordRun(runId, username, llama) {
    return ddb.put({
        TableName: 'Runs',
        Item: {
            RunId: runId,
            User: username,
            llama: llama,
            llamaName: llama.Name,
            RequestTime: new Date().toISOString(),
        },
    }).promise();
}

function toUrlString(buffer) {
    return buffer.toString('base64')
        .replace(/\+/g, '-')
        .replace(/\//g, '_')
        .replace(/=/g, '');
}

function errorResponse(errorMessage, awsRequestId, callback) {
  callback(null, {
    statusCode: 500,
    body: JSON.stringify({
      Error: errorMessage,
      Reference: awsRequestId,
    }),
    headers: {
      'Access-Control-Allow-Origin': '*',
    },
  });
}