var express = require('express');
var formidable = require('formidable');
var fs = require('fs');
var spawn = require('child_process').spawn;

var app = express();

var port = 9001;

app.listen(port, () => {
  console.log("New app listening on " + port);
});

app.use("/stitchify/stitchimg", express.static(__dirname + "/stitchimg"));

app.post("/stitchify/upload", (req, res) => {
    console.log("Request to stitchify/upload");
    var form = new formidable.IncomingForm();
    form.parse(req, (err, fields, files) => {
      console.log(files.infile.path);
      var filepath = "/var/www/noelle.codes/node/stitchimg/" + files.infile.name;
      fs.rename(files.infile.path, filepath, (err) => {
        if (err) {
          console.log("Oh no, err.");
          res.write("<h2>Heck.</h2>");
          res.write("<p>There was a server-side error. Please hit the back button and try again.</p>");
          res.end();
	} else {
          console.log("Uploaded " + files.infile.name);
          var filepath = files.infile.path;
          var process = spawn('python3', ["./stitchify.py",files.infile.name]);
          process.stdout.on("data", (data) => {
            console.log("Successfully converted " + data.toString());
  	    res.write("<img src='stitchimg/" + data.toString() + "'>");
            res.write("<br><br>");
            res.write("<p>(<a href='https://paypal.me/joyeusenoelle' target='_blank'>Did it work? Send me a couple bucks as a thank you!</a>)</p>");
            res.write("<p>(Or <a href='https://patreon.com/noelleanthony'>sign up for my Patreon so I can afford to stay alive and keep writing code like this!</a>)</p>");
            res.end();
          });
        }
      });    
    });
});

app.get("/stitchify", (req, res) => {
    console.log("Request to stitchify");
    res.write("<h2>Stitchify!</h2>");
    res.write("<p>Turn your images into cross-stitch patterns!</p>");
    res.write("<p>At the moment, this tool supports images with up to 52 colors.More than that and it throws a tantrum.</p>");
    res.write("<form action='stitchify/upload' method='post' enctype='multipart/form-data'>");
    res.write("<input type='file' name='infile' accept='image/png, image/jpeg, image/gif'>");
    res.write("<input type='submit'>");
    res.write("</form>");
    res.write("<p>(<a href='https://paypal.me/joyeusenoelle' target='_blank'>Consider sending me a couple bucks as a thank you for writing this and keeping it running!</a>)</p>");
    res.write("<p>(Or <a href='https://patreon.com/noelleanthony'>sign up for my Patreon so I can afford to stay alive and keep writing code like this!</a>)</p>");

    res.end();
}); 

app.get("/", (req, res) => {
    console.log("Generic request");
    res.write("Try going to /stitchify!");
    res.end();
});

