// Include Main HTTP module
var http = require('http');

// Include Formidable libarary for Upload Processing
var formidable = require('formidable');

// Include file system module
var fs = require('fs');

// Function to count punctuations in file
function countPunctuations(punctuationsStrings) {
    let punctuationsCount = 0;
    const punctuations = [".", ",", "!", "?"];
    for (const ch of punctuationsStrings) {
      if (punctuations.includes(ch)) punctuationsCount++;
    }
    return punctuationsCount;
  }

// Create server for listening incoming connections
http.createServer(function (req, res) {
    // File upload check with requested url
    if (req.url == '/fileupload') {
        // Create form object with formidable
        var form = new formidable.IncomingForm();
        // Parse the form
        form.parse(req, function (err, fields, files) {
            // Get file path
            var uploadedFile = files.filetoupload.filepath;
            // Get size file in Bytes
            const fileSizeInBytes = fs.statSync(uploadedFile).size;
            // Get how many words contain in file
            const wordCount = (string) => (string.match(/\S+/g) || []).length;

            //Read file with File System module and show information for it
            fs.readFile(uploadedFile, 'utf8', function(err, data) {
                // If any error then, throw it
                if (err) throw err;

                // Print file info
                console.log("The text in the file:\n\n", data,"\n")

                let result={
                    "Temporary Location": uploadedFile,
                    "File Size": fileSizeInBytes,
                    "Word Count": wordCount(data),
                    "Punctuation Count": countPunctuations(data)
                }
                console.table(result)
            });
            // Successfull confirmation
            res.write('File uploaded!');
            res.end();
        });
    }
    // File upload check with requested url
    else if (req.url == '/fileuploadandsave') {
        // Create form object with formidable
        var form = new formidable.IncomingForm();
        // Parse the form
        form.parse(req, function (err, fields, files) {
            // Get old file path
            var oldpath = files.filetoupload.filepath;
            // Set new file path
            var newpath = 'Path to your location' + files.filetoupload.originalFilename;
            // Move file from old path to new path
            fs.rename(oldpath, newpath, function (err) {
                // If any error then, throw it
                if (err) throw err;
                // Successfull confirmation
                res.write('File uploaded and moved!');
                res.end();
            });
        });
    }
    else {
        // Set header to text/html
        res.writeHead(200, {'Content-Type': 'text/html'});

         // Write response with file upload form 
        res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
        res.write('<input type="file" name="filetoupload"><br>');
        res.write('<input type="submit" value="Upload"<br>')
        res.write('</form>');
        res.write('<hr>')
        res.write('<form action="fileuploadandsave" method="post" enctype="multipart/form-data">');
        res.write('<input type="file" name="filetoupload"><br>');
        res.write('<input type="submit" value="Upload&Save"<br>')
        res.write('</form>');
        return res.end();
    }
}).listen(3000, () => {console.log("Server listening on port 3000")});