let express = require('express')
let router = express.Router()
const auth = require('../lib/auth')

var fs = require("fs");
const rateLimit = require("express-rate-limit");
const { exec } = require('child_process');
const limiter = rateLimit({
    windowMs: 60 * 1000,
    max: 3,
    message: "You are being rate limited"
});
let { User, Sequelize } = require('../models')
const Errors = require('../lib/errors')
var randomString = (Math.random().toString(36).substring(2))
router.use(limiter);
router.post("/refresh", limiter, auth, async(req, res, next) => {
    User.findByPk(req.userData.UserId).then(function(selected){
        var blendFilePath = "../rendering/avatar.blend";
        var imageSavePath = "/usr/share/nginx/html/cdn/user/avatars/full/"+req.userData.UserID+"-"+randomString+".png";
        var pythonFilePath = "../rendering/usercontent/"+req.userData.UserID+".py";
        var faceFilePath = "../rendering/faces/defaultFace.png";
        var imports = "import bpy";
        var functions = "def hex_to_rgb(value):\n    gamma = 2.05\n    value = value.lstrip('#')\n    lv = len(value)\n    fin = list(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))\n    r = pow(fin[0] / 255, gamma)\n    g = pow(fin[1] / 255, gamma)\n    b = pow(fin[2] / 255, gamma)\n    fin.clear()\n    fin.append(r)\n    fin.append(g)\n    fin.append(b)\n    return tuple(fin)";
        var blenderImport = "bpy.ops.wm.open_mainfile(filepath='"+blendFilePath+"')";
        var	headColor = "bpy.data.objects['Head'].select = True\nbpy.data.materials['Head'].diffuse_color = hex_to_rgb('#"+User.headColor+"')\nbpy.data.materials['Face'].diffuse_color = hex_to_rgb('#"+User.headColor+"')";
        var leftArmColor = "bpy.data.objects['Left Arm'].select = True\nbpy.data.objects['Left Arm'].active_material.diffuse_color = hex_to_rgb('#"+User.leftArmColor+"')";
        var rightArmColor = "bpy.data.objects['Right Arm'].select = True\nbpy.data.objects['Right Arm'].active_material.diffuse_color = hex_to_rgb('#"+User.rightArmColor+"')";
        var	torsoColor = "bpy.data.objects['Torso'].select = True\nbpy.data.objects['Torso'].active_material.diffuse_color = hex_to_rgb('#"+User.torsoColor+"')";
        var leftLegColor = "bpy.data.objects['Left Leg'].select = True\nbpy.data.objects['Left Leg'].active_material.diffuse_color = hex_to_rgb('#"+User.leftLegColor+"')";
        var rightLegColor = "bpy.data.objects['Right Leg'].select = True\nbpy.data.objects['Right Leg'].active_material.diffuse_color = hex_to_rgb('#"+User.rightLegColor+"')";
        var colors = headColor+"\n"+leftArmColor+"\n"+torsoColor+"\n"+rightArmColor+"\n"+leftLegColor+"\n"+rightLegColor;
        var face = "face_Image = bpy.data.images.load(filepath = '"+faceFilePath+"')\nbpy.data.textures['Face'].image = face_Image";
        var render = "scene = bpy.context.scene\nscene.render.image_settings.file_format = 'PNG'\nscene.render.filepath = '"+imageSavePath+"'\nbpy.ops.render.render(write_still = 1)";
        var python = imports+"\n"+functions+"\n"+blenderImport+"\n"+colors+"\n"+face+"\n"+render;

        fs.writeFile("../rendering/usercontent/"+req.userData.UserId+".py", python, function(err,data){
            if(err) { console.log(err) }
            console.log(data);
        })

        exec("blender -b -P ../rendering/usercontent/"+req.userData.UserId+".py", (err, stdout, stderr) => {
            if(err) { console.log(err) }
            console.log("stdout: " + stdout);
            console.log("stderr: " + stderr);
        });
    });
});

module.exports = router;
