import random from 'randomstring'
import doc from 'dynamodb-doc'

const dynamo = new doc.DynamoDB()

const generateShortUrl = () => {
  return new Promise((resolve, reject) => {
    const shortUrl = random.generate(7)
    const params = {
      "TableName": "qutto",
      "Key": {
        "shorten": tmp
      }
    }
    dynamo.getItem(params, (err, data) => {
      if (err) {
        reject(err)
      }
      if (data.length < 1) {
        resolve(shortUrl)
      }
      generateUniqUrl().then((shortUrl) => {
        resolve(shortUrl)
      })
    })
  })
}

const save = (url, shortUrl) => {
  return new Promise((resolve, reject) => {
    const params = {
      "TableName": "qutto",
         "Item": {
           "shorten": shortUrl,
           "url": url
         }
    }
    dynamo.putItem(shortenParams, (err, data) => {
      if (err) {
        reject(err)
      }
      resolve({"shorten": shortUrl})
    })
  })
}

const find = (shortUrl) => {
  return new Promise((resolve, reject) => {
    const params = {
      "TableName": "qutto",
      "Key": {
        "shorten": shortUrl
      }
    }
    dynamo.getItem(params, (err, data) => {
      if (err) {
        reject(err)
      }
      resolve(data)
    })
  })
}

exports.handler = (event, context) => {

  const operation = event.operation

  switch (operation) {
    case 'shorten':
      generateShortUrl()
        .then((shortUrl) => save(event.url, shortUrl))
        .then((result) => context.succeed(result))
        .catch((error) => context.fail(error))
      break
    case 'deshorten':
      find(event.shorten)
        .then((result) => context.succeed(result))
        .catch((error) => context.fail(error))
      break
  }

}

@@ -298,11 +298,16 @@
 n%22: 
-tmp
+shortUrl
 %0A   
@@ -402,24 +402,72 @@
 rr)%0A      %7D%0A
+      console.log(data)%0A      resolve(shortUrl)%0A
       if (da
@@ -535,12 +535,13 @@
 rate
-Uniq
+Short
 Url(
@@ -853,16 +853,9 @@
 tem(
-shortenP
+p
 aram

Fix typo