'use strict';

const AWS = require('aws-sdk');
const gm = require('gm').subClass({ imageMagick: true });
const fetch = require('node-fetch');
const Libra = require('./libra');
const s3 = new AWS.S3();

module.exports.info = (event, context, callback) => {
  const url = event.url;
  const libra = new Libra(url);
  libra.getData().then(data => {
    console.log('=============================');
    console.log(data);
    callback(null, data);
  });
};

module.exports.thumb = (event, context, callback) => {
  const itemId = event.pocket_id;
  const suggested = event.suggested
  const item10Id = `0000000000${itemId}`.substr(-10, 10);
  const itemId3 = item10Id.slice(0, 3);
  const s3path = `items/thumbs/${itemId3}/${item10Id}.jpg`;
  console.log('S3 Path --', s3path);
  try {
    const libra = new Libra(event.url);
    libra.getData().then(data => {
      let imageUrl = suggested ? suggested : data.image;
      console.log('Detected image URL --', imageUrl);
      fetch(imageUrl)
        .then(response => {
          if (response.ok) {
            response.buffer().then(buffer => {
              gm(buffer)
                .resize(420)
                .background('#fff')
                .flatten()
                .toBuffer('jpg', (err, buf) => {
                  console.log('Resized Buffer --', buf);
                  putImage(s3path, buf).promise()
                    .then(v => callback(null, v));
                });
            })
          }
        }, err => {
          putBlankImage(s3path);
          callback(null, 'Done.');
        });
    })
  } catch (e) {
    putBlankImage(s3path);
    callback(null, 'Done.');
  }
};

function putBlankImage(s3path) {
  console.log('Fetch failed. Using blank image.');
  gm('./blank.jpg').toBuffer('jpg', (err, buf) => {
    console.log('Blank image Buffer --', buf);
    putImage(s3path, buf);
  });
}

function putImage(s3path, buffer) {
  console.log(`Putting image on S3 (${s3path}):`, buffer);
  return s3.putObject({
    Bucket: process.env.BUCKET,
    Key: s3path,
    Body: buffer,
  }, (err, data) => {
    if (err) { console.log('Error:', err); }
    if (data) { console.log('Success:', data); }
  });
}

@@ -776,16 +776,110 @@
   try %7B%0A
+    if (suggested) %7B%0A      fetchAndConvertAndPut(s3path, suggested, callback);%0A    %7D else %7B%0A  
     cons
@@ -914,16 +914,18 @@
 l);%0A    
+  
 libra.ge
@@ -957,63 +957,220 @@
     
-let imageUrl = suggested ? suggested : data.image;%0A    
+  fetchAndConvertAndPut(s3path, data.image, callback);%0A      %7D);%0A    %7D%0A  %7D catch (e) %7B%0A    putBlankImage(s3path);%0A    callback(null, 'Done.');%0A  %7D%0A%7D;%0A%0Afunction fetchAndConvertAndPut(s3path, imageUrl, callback) %7B%0A
   co
@@ -1215,20 +1215,16 @@
 geUrl);%0A
-    
   fetch(
@@ -1233,20 +1233,16 @@
 ageUrl)%0A
-    
     .the
@@ -1263,20 +1263,16 @@
 %7B%0A      
-   
- 
 if (resp
@@ -1282,20 +1282,16 @@
 e.ok) %7B%0A
-    
         
@@ -1335,20 +1335,16 @@
         
-  
-  
 gm(buffe
@@ -1346,20 +1346,16 @@
 buffer)%0A
-    
         
@@ -1383,20 +1383,16 @@
         
- 
-   
 .backgro
@@ -1403,20 +1403,16 @@
 '#fff')%0A
-    
         
@@ -1438,20 +1438,16 @@
         
-    
 .toBuffe
@@ -1485,20 +1485,16 @@
         
-   
- 
 console.
@@ -1538,20 +1538,16 @@
         
-    
 putImage
@@ -1586,20 +1586,16 @@
         
-  
-  
 .then(v 
@@ -1625,28 +1625,24 @@
             
-    
 %7D);%0A        
@@ -1641,20 +1641,16 @@
         
-   
- 
 %7D)%0A     
@@ -1654,22 +1654,14 @@
     
-    
 %7D%0A    
- 
-   
 %7D, e
@@ -1664,28 +1664,24 @@
 %7D, err =%3E %7B%0A
-    
       putBla
@@ -1703,20 +1703,16 @@
 ;%0A      
-    
 callback
@@ -1736,101 +1736,13 @@
     
-   
- 
 %7D);%0A
-    %7D)%0A  %7D catch (e) %7B%0A    putBlankImage(s3path);%0A    callback(null, 'Done.');%0A  %7D%0A%7D;
+%7D
 %0A%0Afu

use suggested first