/*
 * saucenao.js - grab a image's source using saucenao. Grabs the last message attachment/URL, provided along with the command
 * or providing an attachment using the command as the caption.
 * 
 *  Contributed by Capuccino
 */

/* eslint-env node */

//this handles the SauceNao handling
const saucenao = require('./sauceQueryHandler');
let ayaneru;

exports.init = bot => {
    ayaneru = new saucenao({key: bot.config.sauceKey});
}
//this regex is gay

const urlRegex = str => /(http(s)?:\/\/)?(www\.)?[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi.test(str);

exports.commands = [
    'saucenao'
];

exports.saucenao = {
    desc: 'Gets the image from the recent attachment or via a image link and looks for saucenao to check for the source of the image.',
    main(bot, ctx) { 
        return new Promise((resolve, reject) => {
            if (!ctx.attachments[0]) {
                return ctx.createMessage('Aw, no image here.');
            } else if (!ctx.suffix === urlRegex) {
                return ctx.createMessage('Oi, your URL is invalid!');
            } else if (ctx.attachments[0]) {
                ayaneru.getSauce(ctx.attachments[0].url).then(res => {

                }).catch(reject);
            } else if (ctx.suffix) {
                ayaneru.getSauce(ctx.suffix).then(res => {
                    let ovy = JSON.parse(res.results);
                    for (ovy.data of ovy) {
                        const fields = [];
                        fields.push(`${{name: ovy.title, value: ovy.thumbnail, inline: true}}`, 0);
                        ctx.createMessage({embed: {
                            title: 'saucenao query',
                            description: 'this is what we can find from your image.',
                            fields
                        }})
                    }
                }).catch(reject);
            }
        });
    }
};
@@ -428,17 +428,18 @@
 Key%7D);%0A%7D
+;
 %0A
-
 //this r
@@ -1204,17 +1204,435 @@
 es =%3E %7B%0A
+                    let fields =%5B%5D;%0A                    for (res.url in res) %7B%0A                        fields.push(%60$%7B%7Bname: res.name, value: %60(Link)%5B$%7Bres.url%7D%5D%60%7D%7D%60, 0);%0A                    %7D%0A                    ctx.createMessage(%7Bembed: %7B%0A                        title: 'Saucenao query results',%0A                        description: 'this is what we can find',%0A                        fields%0A                    %7D%7D);
 %0A
-
         
@@ -2213,32 +2213,32 @@
          fields%0A
-
                 
@@ -2248,16 +2248,17 @@
      %7D%7D)
+;
 %0A       

complete Saucenao programmatically