var mongoose           = require('mongoose');
var db                 = mongoose.connect('mongodb://localhost/leafAlone');
var Schema             = mongoose.Schema;

var userSchema  = new Schema({
                            email:          String,
                            pw:             String,
                            deviceID:       String,
                            fname:          String,
                            lname:          String,
                            pNum:           String,
                            pCarrier:       String,
                            plantName:      String,
                        });

var plantSchema = new Schema({

                            plantName:      String,
                            ecMin:          String,
                            ecMax:          String,
                            phMin:          String,
                            phMax:          String,
                            });


var entrySchema = new Schema({
                                timestamp:       Date,
                                deviceID:        String,
                                IP_Address:      String,
                                ph:              String,
                                ec:              String,
                                photoResistor:   String,
                                waterLevel:      String,
                                minPh:           String,
                                maxPh:           String,
                                minEc:           String,
                                maxEc:           String
                        });

var entryModel = mongoose.model('entry', entrySchema);
var plantModel = mongoose.model('plant', plantSchema);
var userModel = mongoose.model('users', userSchema);



exports.addEntry = function(data, cb) {

    var entry = new entryModel();

    entry.timestamp     = data[0];
    entry.deviceID      = data[1];
    entry.IP_Address    = data[2];
    entry.ph            = data[3] 
    entry.ec            = data[4]
    entry.waterLevel    = data[5];
    entry.photoResistor = data[6];
    entry.minPh         = data[10]
    entry.maxPh         = data[11]
    entry.minEc         = data[12]
    entry.maxEc         = data[13]

    entry.save(function(err, user) {

        if(err) {
            console.error(err);
        }
        else {
            console.log("Entry saved Successfully");
        }

        entryModel.find({IP_Address: data[2]}, function(err, entries) {

            if(err) {
                console.error(err);
                cb(null);
            }
            else {
                cb(entries);
            }
            
        });
    });

}


exports.allEntries = function(deviceID, cb) {

    entryModel.find({deviceID: deviceID}, function(err, entries) {

            if(err) {
                console.error(err);
                cb(null);
            }
            else {
                cb(entries);
            }
            
        });
}

exports.updateUser = function(user, email, pw, deviceID, fname, lname, pNum, pCarrier, plantName, cb) {


    var flag = false;

    userModel.findOne({"email": user.email}, function (err, user) {

    if(!user) {
        return cb(null, null);
    }

    else {

    user.email     = email;
    user.pw        = pw;
    user.fname     = fname;
    user.lname     = lname;
    user.pNum      = pNum;
    user.pCarrier  = pCarrier;

    if(plantName != user.plantName) {

        flag = true;
    }

    user.plantName = plantName;
    user.deviceID  = deviceID;

    //Save user in DB
    user.save(function(err,user){

        if (err) {
            console.error("Error Updating User : " + email + " - " + err);
            cb(err, null);
        } else {
            console.log("User Updated " + user);

            if(flag) {

                cb("plant", user);
            }
            else {
            cb(null, user);
        }
        }


    });


    }
});

}

//Create demo Users and plants
userModel.findOne({"email": "testUser"}, function (err, user) {

    if(!user) {
        createUser("testUser", "password", "123",  "Matt", "DiLeonardo", "4075555555", "ATT", "Tomato", function(err) {
        });
    }
});

plantModel.findOne({"plantName": "tomato"}, function(err, plant) {

    if(!plant) {

        addPlant("tomato","5.8", "7.0", "1000", "2000");

    }

});

plantModel.findOne({"plantName": "pepper"}, function(err, plant) {

    if(!plant) {

        addPlant("pepper","5.7", "6.8", "1000", "2500");

    }

});

plantModel.findOne({"plantName": "basil"}, function(err, plant) {

    if(!plant) {

        addPlant("basil","5.6", "6.8", "700", "1500");

    }

});

plantModel.findOne({"plantName": "rosemary"}, function(err, plant) {

    if(!plant) {

        addPlant("rosemary","5.8", "6.5", "700", "1500");

    }

});

exports.findPlant = function(plantName, cb) {

    plantModel.findOne({"plantName": plantName}, function(err, plant) {

    if(!plant) {

        console.log(plantName);

    }
    else {

        cb(plant);
    }

    });
}

function addPlant(plantName, phMin, phMax, ecMin, ecMax) {

    var plant = new plantModel();

        plant.plantName = plantName;
        plant.phMin     = phMin;
        plant.ecMin     = ecMin;
        plant.phMax     = phMax;
        plant.ecMax     = ecMax;

        plant.save(function(err, plant) {

            if(err) {

                console.log(err);
            }

            else {

                console.log("Plant Created:" + plant);
            }
        });
}

exports.findById = function(id, cb) {


    userModel.findOne({"_id":id}, function(err,user){

        if (err) throw err;

        if(!user){
            return cb(new Error('User does not exist'));
        }
        //User is found in database
        else{
            return cb(null, user);
        }
    });
};

exports.findUser = function(username, pw, cb) {

    console.log(username);
    console.log(pw);

    userModel.findOne({"email":username}, function(err,user){

        if (err) throw err;

        if(!user){

            return cb(null, null);
        }
        
        //User is found in database
        else {

            if(user.pw == pw) {
                return cb(null, user);
            }

            else {
                return cb(null, null);
            }
        }
    });
};

//Creates a user
exports.createUser = function (email, pw, deviceID, fname, lname, pNum, pCarrier, plantName, cb){

    //Check if user exists already
    userModel.findOne({"email":email}, function(err,user){

        if (err) {

            console.log(err);
            cb(null,null);
        }
        if(user == null){

            createUser(email, pw, deviceID, fname, lname, pNum, pCarrier, plantName, cb);
        }
        else{
            console.log("Email Already Exists");
            cb(new Error("Email Already Exists"), null);
            
        }
    });
};

function createUser(email, pw, deviceID, fname, lname, pNum, pCarrier, plantName, cb){
    var user = new userModel();

    user.email        = email;
    user.pw           = pw;
    user.fname     = fname;
    user.lname     = lname;
    user.pNum      = pNum;
    user.pCarrier  = pCarrier;
    user.plantName = plantName;
    user.deviceID  = deviceID;

    //Save user in DB
    user.save(function(err,user){

        if (err) {
            console.error("Error Creating User : " + email + " - " + err);
            cb(err, null);
        } else {
            console.log("User created " + user);
            cb(null, user);
        }

    });
  
};