var express = require('express');
var app = express();
var multer = require('multer')
var cors = require('cors');
var bodyParser = require("body-parser");
var https = require('https')
var csv = require('csv');
const { parse } = require("csv-parse");
const util = require('util');
const fs = require('fs');

var corsOptions = {
    "origin": "*",
    "methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
    "preflightContinue": false,
    "optionsSuccessStatus": 204
}
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors(corsOptions));

function callLoadInitializeData(req, res, resdata){

    _email = req.query.email;

    let url = `https://openshield.ts.bizside.biz/loadInitializeData?projectid=23&construction_id=${resdata.construction_id}&username=${_email}&sheetname=${resdata.file_type}&filename=${resdata.file_name}`

    console.log(url);

    https.get(url, (resp) => {
        let data = '';

    // A chunk of data has been received.
        resp.on('data', (chunk) => {
            data += chunk;
        });

        // The whole response has been received. Print out the result.
        resp.on('end', () => {
            if(data !== 'no match'){

                resdata = JSON.parse(data);
                console.log(resdata.status);
                if(resdata.status=="complete"){
                    res.status(200).send('OK');
                }else if(resdata.status=="INSERT ERROR"){
                    console.log("insert error");
                    res.status(204).send("insert error");
                }
                
            }
            
        });

        }).on("error", (err) => {
        console.log("Error: " + err.message);
        });
}

function callInitFileMover(req, res) {
    https.get('https://openshield.ts.bizside.biz/iniFileMover', (resp) => {
        let data = '';

    // A chunk of data has been received.
        resp.on('data', (chunk) => {
            data += chunk;
        });

        // The whole response has been received. Print out the result.
        resp.on('end', () => {
            //debug
            // data = `{
            //     "construction_id": 3,
            //     "file_name": "ini_データ入力シート.xlsx",
            //     "file_type": "dataSheet" 
            // }`
            if(data !== 'no match'){
                resdata = JSON.parse(data);
                console.log(resdata);
                callLoadInitializeData(req, res, resdata);
            }
            
        });

        }).on("error", (err) => {
        console.log("Error: " + err.message);
        });

}

var storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, '/var/www/html/FBS')
    },
    filename: function(req, file, cb) {
        cb(null, file.originalname)
    }
})


var upload = multer({ storage: storage }).single('file')

app.post('/upload', function(req, res, next) {

    console.log('email is ' + req.query.email);

    upload(req, res, function(err) {
        if (err instanceof multer.MulterError) {
            return res.status(500).json(err)
        } else if (err) {
            return res.status(500).json(err)
        }
        else {
            var FileName = req.file.filename;
            callInitFileMover(req, res);
            //res.status(200).send(FileName);
        }
        //return res.status(200).send(req.file)

    })

});

const converter = require('json-2-csv');


app.post('/csv', (req, res, next) => {
    let _res = "";
    const csv = req;
    userData = req.body;

    converter.json2csv(userData, (err, csv) => {
        if (err) {
            throw err;
        }

        let _userData = userData;
        _userEmail = _userData[0].mailadress;
        _jsessionid = _userData[0].jsessionid;
        console.log("--- user data ----", _userData[0].mailadress);
        //check for record alredy exist
        try {
            const path = '/var/www/html/appexe/natnats/23/bin/mobileweb2/resources/database/user_record.csv';
            if (fs.existsSync(path)) {
                fs.createReadStream(path)
                .pipe(parse({ delimiter: ",", from_line: 2 }))
                .on("data", function (row) {
                    
                    console.log("--- r-0 ----", row[0]);
                    if(row[0] === _userEmail){
                        _res = row[2];
                    }

                    console.log("--- _res ----", _res);
    
                    if(_res === ""){
                        console.log("--- appending file ----", _res);
                        fs.appendFile(path, csv, function (err) {
                            if (err) throw err;
                            console.log('The "data to append" was appended to file!');
                        });
                        _res = 'OK';
                        //writetoFile(csv);
                    }
                    res.send({'id': _res});

                });
                if(_res === ""){
                    writetoFile(csv);
                    _res = _jsessionid;
                    res.send({'id': _res});
                }
            }
          } catch(err) {
            console.log("---error -----");
            writetoFile(csv);
            console.error(err)
            res.send({'erro': err});
          }
        // print CSV string
        //console.log(csv);
    });
    //console.log("---sending res -----");
    //res.send({'id': _res});
});

function writetoFile(csv) {
    fs.writeFile('/var/www/html/appexe/natnats/23/bin/mobileweb2/resources/database/user_record.csv', csv, err => {
        if (err) {
            console.error(err)
            return
        }
    })
}

app.listen(8000, function() {
    console.log('App running on port 8000');

});
