var dbUsers = require('../db/users');
var net = require('net');


exports.cc3000 = function(req, res) {

    console.log(req.params.test);

    res.render("cc3000", {user: req.user});
}


exports.addEntry = function(req, res) {

    console.log(req.params.data);

    var temp = req.params.data.split(",");

    var strings = [Date(), temp[0], temp[1], temp[2], temp[3], temp[4], temp[5], "N/A", "N/A", "N/A", temp[6], temp[7], temp[8], temp[9]];


        console.log(strings);

        if (strings[3] != "N/A") {

            var neg = 1;

            if(strings[3] < 0) {

                neg = -1;

                console.log("**** EMAIL/SMS sent to refill pH buffer *****");
            }

            setPhValue(strings[3]* neg, function(data) {

                strings[3] = data;

            });
        }

        if (strings[4] != "N/A") {

            var neg1 = 1;

            if(strings[4] < 0) {

                neg1 = -1;

                console.log("**** EMAIL/SMS sent to refill nutrient liquid *****");
            }

            setEcValue(strings[4]* neg1, function(data) {

                strings[4] = data;

            });
        }

        if(strings[5] < 100) {

            console.log("**** EMAIL/SMS sent to check water level *****");
        }

        setPhValue(strings[10], function(data) {

            strings[10] = data;

            setPhValue(strings[11], function(data) {

                strings[11] = data;

                setEcValue(strings[12], function(data) {

                    strings[12] = data;

                    setEcValue(strings[13], function(data) {

                        strings[13] = data;

                     });
                });
            });
        });

        dbUsers.addEntry(strings, function(allEntries) {

            if(allEntries != null) {

                console.log("Entry added!!");
            }

            else {
                console.log("ERROR RETURNING ENTRIES");
            }
        });


    res.render("fromSystem", {user: req.user});

}

exports.updateAccount = function(req,res) {

    var email     = req.body.email || 0; 
    var pw     = req.body.pw || 0; 
    var deviceID     = req.body.deviceID || 0;
    var fname     = req.body.fname || "Not Specified"; 
    var lname     = req.body.lname || "Not Specified"; 
    var pNum     = req.body.pNum || "Not Specified"; 
    var pCarrier     = req.body.pCarrier || "Not Specified";
    var plantName = req.body.plantName || "Not Specified"; 

    if(email == 0 || pw == 0 || deviceID == 0) {

        console.log("BAD UPDATE");
        res.render('account', {user: req.user, message: "Please Enter a Valid Email, Password, and Device ID"});
    } 

    else{

        dbUsers.updateUser(req.user, email, pw, deviceID, fname, lname, pNum, pCarrier, plantName, function(err, user) {

            if(err && err != "plant") {
                console.log(err);
               res.render('account', {user: req.user, message: err});
            }
            else if (err == "plant") {


                dbUsers.findPlant(user.plantName, function(plant1) {

                    console.log(plant1);

                    translateValues(plant1, function(plant) {


                            var HOST = '192.168.0.103';
                            var PORT = 7;

                           // var dataString =  Date() + ",";

                            var client = new net.Socket();

                        client.connect(PORT, HOST, function() {

                            console.log('CONNECTED TO: ' + HOST + ':' + PORT);
                            // Write a message to the socket as soon as the client is connected, the server will receive it as message from the client 

                            var values = "plant." + plant.phMin + "." + plant.phMax + "'" + plant.ecMin + "'" + plant.ecMax;

                            if(values == 0) {

                                values = " ";
                            }
                            console.log(values);
                            client.write(values);

                        });

                        // Add a 'data' event handler for the client socket
                        // data is what the server sent to this socket
                        client.on('data', function(data) {
                            
                            console.log('DATA: ' + data);

                        });

                        client.on('error', function(err) {

                            console.error(err);
                        });

                        // Add a 'close' event handler for the client socket
                        client.on('close', function() {
                            console.log('Connection closed');

            
                                res.render("home", {user: req.user, message: "Update Successful!"});
                        });
                    });    
                });

                       
            }

            else {
                console.log("Successful");

                req.logIn(user, function(err) {
                    if(err) {
                        console.error(err);
                    } else {

                            res.render("home", {user: req.user, message: "Update Successful!"});
                    }
                });

            }
        });
    }

}

exports.afterLoginPage = function(req,res) {

            res.render("home", {user: req.user});

}

exports.dataLog = function(req,res) {

    dbUsers.allEntries(req.user.deviceID, function(entries) {

        
            res.render("dataLog", {user: req.user, data: entries});

    });
}

function translateValues(plant, cb) {



    plant.phMin = Math.floor((1-(plant.phMin/14))*1024);
    plant.phMax = Math.floor((1-(plant.phMax/14))*1024);

    plant.ecMin = Math.floor(plant.ecMin*1024/3000);
    plant.ecMax = Math.floor(plant.ecMax*1024/3000);


    cb(plant);


}

exports.register = function(req, res) {

    res.render("registerPage", {user: req.user});
}

exports.demo2 = function(req, res) {

    res.render("demo2",{user: req.user});
}

exports.demo2Results = function(req,res) {

    var timeInterval = req.body.timeInterval || 0;
    var numTests     = req.body.numTests || 0;

    if(timeInterval == 0 || numTests == 0) {

        res.render("demo2", {user: req.user, message: "Please enter a value for time interval and number of tests."});
    }

    else {


            var HOST = '192.168.0.103';
            var PORT = 7;

            var dataString =  Date() + ",";

            var client = new net.Socket();

        client.connect(PORT, HOST, function() {

            console.log('CONNECTED TO: ' + HOST + ':' + PORT);
            // Write a message to the socket as soon as the client is connected, the server will receive it as message from the client 

            var values = "demo," + timeInterval + "," + numTests;

            if(values == 0) {

                values = " ";
            }
            console.log(values);
            client.write(values);

        });

        // Add a 'data' event handler for the client socket
        // data is what the server sent to this socket
        client.on('data', function(data) {
            
            console.log('DATA: ' + data);

            dataString += data;
            
        });

        client.on('error', function(err) {

            console.error(err);
        });

        // Add a 'close' event handler for the client socket
        client.on('close', function() {
            console.log('Connection closed');

            res.render("demo2Results", {user: req.user, timeInterval: timeInterval});
       });    
    }
}

exports.testData = function(req, res) {

    var ph     = req.body.pHTest || 0; 
    var ec     = req.body.ECTest || 0;
    var wl     = req.body.waterLevelTest  || 0;
    //var temp   = req.body.tempTest || 0;
    var pt     = req.body.phototransTest || 0;
    //var ap1    = req.body.airpump1 || 0;
    var ap2    = req.body.airpump2 || 0;
    var ecpump = req.body.ecpump || 0;
    var phpump = req.body.phpump || 0;

    var HOST = '192.168.0.103';
    var PORT = 7;

    var dataString =  Date() + ",";

    var client = new net.Socket();
    client.connect(PORT, HOST, function() {

        console.log('CONNECTED TO: ' + HOST + ':' + PORT);
        // Write a message to the socket as soon as the client is connected, the server will receive it as message from the client 

        var values = ph + ec + wl + pt + ap2 + ecpump + phpump;

        if(values == 0) {

            values = " ";
        }
        console.log(ph + ec + wl + pt + ap2 + ecpump + phpump);
        client.write(values);

        });

    // Add a 'data' event handler for the client socket
    // data is what the server sent to this socket
    client.on('data', function(data) {
        
        console.log('DATA: ' + data);

        dataString += data;
        
    });

    client.on('error', function(err) {

        console.error(err);
    });

    // Add a 'close' event handler for the client socket
    client.on('close', function() {
        console.log('Connection closed');
        console.log(dataString);

        var strings = dataString.split(",");
        console.log(strings);

        if (strings[3] != "N/A") {

            var neg2 = 1;

            if(strings[3] < 0) {

                neg2 = -1;

                console.log("**** EMAIL/SMS sent to refill pH buffer *****");
            }

            setPhValue(strings[3] * neg2, function(data) {

                strings[3] = data;

            });
        }

        if (strings[4] != "N/A") {

            var neg3 = 1;

            if(strings[4] < 0) {

                neg3 = -1;

                console.log("**** EMAIL/SMS sent to refill nutrient liquid *****");
            }

            setEcValue(strings[4]* neg3, function(data) {

                strings[4] = data;

            });
        }

        if(strings[5] < 100) {

            console.log("**** EMAIL/SMS sent to check water level *****");
        }

        setPhValue(strings[10], function(data) {

            strings[10] = data;

            setPhValue(strings[11], function(data) {

                strings[11] = data;

                setEcValue(strings[12], function(data) {

                    strings[12] = data;

                    setEcValue(strings[13], function(data) {

                        strings[13] = data;

                     });
                });
            });
        });

        dbUsers.addEntry(strings, function(allEntries) {

            if(allEntries != null) {

                res.render('dataLog', {user: req.user, styles: admin_styles, data: allEntries});
            }

            else {
                console.log("ERROR RETURNING ENTRIES");
            }
        });


    });

}

function setPhValue(value, cb) {

    var temp = (14)*(1-(value/1024)); 

    temp = Math.round(temp * 100)/100;

    cb(temp);

}

function setEcValue(value, cb) {

    var temp = 3000*(value)/1024;

    temp = Math.round(temp *10000)/10000;

    cb(temp);

}

exports.addNewUser = function(req, res) {

    var email     = req.body.email || 0; 
    var pw     = req.body.pw || 0; 
    var deviceID     = req.body.deviceID || 0;
    var fname     = req.body.fname || "Not Specified"; 
    var lname     = req.body.lname || "Not Specified"; 
    var pNum     = req.body.pNum || "Not Specified"; 
    var pCarrier     = req.body.pCarrier || "Not Specified";
    var plantName = req.body.plantName || "Not Specified"; 

    if(email == 0 || pw == 0 || deviceID == 0) {

        console.log("BAD REGISTRATION");
        res.render('registerPage', {user: req.user, message: "Please Enter a Valid Email, Password, and Device ID"});
    } 

    else{

        dbUsers.createUser(email, pw, deviceID, fname, lname, pNum, pCarrier, plantName, function(err, user) {

            if(err) {
                console.log(err);
               res.render('registerPage', {user: req.user, message: err});
            }
            else {
                console.log("Successful");

                req.logIn(user, function(err) {
                    if(err) {
                        console.error(err);
                    }
                    else if(user.plantName != "Not Specified") {

                        dbUsers.findPlant(user.plantName, function(plant1) {

                            translateValues(plant1, function(plant) {

                                    var HOST = '192.168.0.103';
                                    var PORT = 7;

                                   // var dataString =  Date() + ",";

                                    var client = new net.Socket();

                                client.connect(PORT, HOST, function() {

                                    console.log('CONNECTED TO: ' + HOST + ':' + PORT);
                                    // Write a message to the socket as soon as the client is connected, the server will receive it as message from the client 

                                    var values = "plant." + plant.phMin + "." + plant.phMax + "'" + plant.ecMin + "'" + plant.ecMax;

                                    if(values == 0) {

                                        values = " ";
                                    }
                                    console.log(values);
                                    client.write(values);

                                });

                                // Add a 'data' event handler for the client socket
                                // data is what the server sent to this socket
                                client.on('data', function(data) {
                                    
                                    console.log('DATA: ' + data);

                                    
                                });

                                client.on('error', function(err) {

                                    console.error(err);
                                });

                                // Add a 'close' event handler for the client socket
                                client.on('close', function() {
                                    console.log('Connection closed');
                                   
                                        res.render("home", {user: req.user});
                                });
                            });    
                        });
                    }
                     else {

                            res.render("home", {user: req.user});

                    }
                });

            }
        });
    }

    


}


exports.logout = function(req, res){
    req.logout();
    res.redirect('/');
};

exports.account = function(req, res){

    accountInfo(req.user.pCarrier, req.user.plantName, function(carrierIndex, plantIndex) {


        res.render('users/account', { user: req.user, carrier: carrierIndex, plant: plantIndex});
    });

};

function accountInfo(carrier, plant, cb) {

    var carriers = ["@text.wireless.alltel.com" ,"@txt.att.net","@myboostmobile.com", "@sms.mycricket.com",
                    "@mymetropcs.com", "@messaging.sprintpcs.com", "@page.nextel.com","@VTEXT.com","@tmomail.net",
                    "@email.uscc.net", "@vtext.com", "@vmobl.com"];

    var plants = ["tomato", "pepper", "basil", "rosemary"];

    var carrierIndex;
    var plantIndex;
    var i = 0;

    for ( i =0; i < carriers.length; i ++) {

        if(carrier == carriers[i]) {

            carrierIndex = i;
        }
    }

    for (i =0; i < plants.length; i ++) {

        if(plant == plants[i]) {

            plantIndex = i;
        }
    }

    return cb(carrierIndex, plantIndex);

}
