var config = require('./config.js') || require('./server-config.js');
var express = require('express');
var app = express();
var hb = require('express3-handlebars');
var http = require("http");
var bodyparser = require("body-parser");
var m = require("mongodb");
var ObjectID = m.ObjectID;
var mConfig = config.mongo;
var PROD = false;
var w = require('winston');

w.add(w.transports.File, { filename: './error.log' });


var db = new m.Db(mConfig.db, new m.Server(mConfig.domain, mConfig.port),{safe:false});

db.open(function(err, client) {
    if (mConfig.user) {
    client.authenticate(mConfig.user, mConfig.pass, function(err, success) {
        knockoutCollection = db.collection("knockout");
        w.log("error","Connection error",err);
    });
    }
    else {
        w.info('success db');
        knockoutCollection = db.collection("knockout");
    }
});

app.engine('hbs', hb({extname:'hbs',defaultLayout:"empty.hbs"}));
app.set('view engine', 'hbs');
app.use(bodyparser());
app.use("/",express.static(__dirname + "/public_html"));

app.get('/greetings', function(req, res){
  res.render('index',{greeting:randElement(greetings),title:req.url});
});

app.get("/request",function(req,res){
    var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress || 
    req.socket.remoteAddress ||
    req.connection.socket.remoteAddress;
    
    var greeting = randElement(greetings);
    res.writeHead(200, {
  'Content-Type': 'text/html' });
  res.end("<html><head>" + "<meta charset='UTF-8'>" + "</head><body>" + greeting + "</body></html>");
});

app.get("/test", function(req,res){
    if (!knockoutCollection) {
        res.end("No knockoutCollection");
        return;
       }
    else {
    knockoutCollection.find().toArray(function(err, items) {
        if (err) {
            res.end("There was an error");
            w.log("error","Error finding", err);
        }
        res.end("success");
    });
    }
});

app.get("/knockout",function(req,res){
    res.render('knockout',{'greeting':randElement(greetings)});
});

app.post("/knockout/save",function(req,res){
    var cat = req.body.cat;
    if (cat) {
        knockoutCollection.insert({cat:cat},{w:1}, function(err, result) {
            if (err) {
                res.json({txt:err});
            }
            else {
                res.json({txt:"Successfully saved category " + cat});
            }
        });
    }
    else {
        res.json({txt:"Error saving category " + cat});
    }
});

app.get("/knockout/load",function(req,res){
    var val = req.query.x;
    knockoutCollection.find().toArray(function(err, items) {
        if (err) {
            res.json({txt:'error'});
            return;
        }
        res.json(items);
    });
   
});

app.post("/knockout/del",function(req,res){
    var selector;
    if (req.body.id) {
        selector = {"_id":ObjectID(req.body.id)};
    }
    knockoutCollection.remove(selector,{w:1},function(err,result){
        if (err) {
            res.json({txt:err});
        }
        else {
            res.json({txt:result + " category documents have been deleted."});
        }
    });
});

app.listen(3000);

var greetings = ["Hello","こんにちは","夜露死苦"];

function randElement(ary) {
        return ary[Math.floor(Math.random() * ary.length)];
    }

@@ -361,445 +361,375 @@
 ');%0A
-%0Aw.add(w.transports.File, %7B filename: './error.log' %7D);%0A%0A%0Avar db = new m.Db(mConfig.db, new m.Server(mConfig.domain, mConfig.port),%7Bsafe:false%7D);%0A%0Adb.open(function(err, client) %7B%0A    if (mConfig.user) %7B%0A    client.authenticate(mConfig.user, mConfig.pass, function(err, success) %7B%0A        knockoutCollection = db.collection(%22knockout%22);%0A        w.log(%22error%22,%22Conne
+var dbUrl = %22%22;%0Avar knockoutCollection;%0A%0Aif (PROD) %7B%0A    dbUrl = mConfig.remoteDb;%0A%7D%0Aelse %7B%0A     dbUrl = %22mongodb://%22 + mConfig.host + %22:%22 + mConfig.port + %22/%22 + mConfig.db;%0A%7D%0A%0Aw.add(w.transports.File, %7B filename: './error.log' %7D);%0A%0Am.MongoClient.connect(dbUrl, %7Bdb : %7Bnative_parser: false, server: %7BsocketOptions: %7BconnectTimeoutMS: 500%7D%7D%7D%7D, %0A    fun
 ction
- error%22,err);%0A    %7D);%0A    %7D%0A    else %7B%0A        w.info('success db');
+(err, db) %7B
 %0A   
@@ -781,22 +781,16 @@
 kout%22);%0A
-    %7D%0A
 %7D);%0A%0Aapp

use mongoclient to connect