var http = require("http");
var express = require("express");
var app = express();
var fs = require("fs");
var path = require("path");

var port = process.env.PORT || process.env.OPENSHIFT_NODEJS_PORT || 8080;

var mongoClient = require('mongodb').MongoClient,
    assert = require('assert');

//var mongodb = "mongodb://localhost:27017/kapparr";
var mongodb = "mongodb://kapparr:123@ds119568.mlab.com:19568/heroku_9pf31s17";

mongoClient.connect(mongodb, function(err, db) {
    assert.equal(null, err);
    console.log("Connected successfully");
    db.close();
});

app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname + '/public/index.html'));
});

var re_weburl = new RegExp("^" + "(?:(?:https?|ftp)://)" + "(?:\\S+(?::\\S*)?@)?" + "(?:" + "(?!(?:10|127)(?:\\.\\d{1,3}){3})" + "(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})" + "(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})" + "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" + "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" + "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" + "|" + "(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)" + "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*" + "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" + "\\.?" + ")" + "(?::\\d{2,5})?" + "(?:[/?#]\\S*)?" + "$", "i");


app.get(/\/api\//, function(req, res) {
    var url = req.url.substring(5);
    console.log(url);
    //res.send(url);
    if (url.match(re_weburl)) {
        var hash = Math.abs(url.hashCode()).toString(36);

        var doc = {
            "shortened": hash,
            "url": url
        };
        mongoClient.connect(mongodb, function(err, db) {
            findUrl(db, url, function(callback) {
                if (callback.length == 0) {
                    console.log(url + "will be added to DB");
                    findShortened(db, url, function(callback) {
                        if (callback.length == 0) {
                            addDocument(db, doc, function() {
                                db.close();
                            });
                        } else {
                            doc.shortened = hash + Math.abs(callback.length).toString(36);
                            addDocument(db, doc, function() {
                                res.send("http://κ.ga/" + doc.shortened);
                                db.close();
                            });
                        }
                    });
                }
            });
        });
        res.send("http://κ.ga/" + hash);
    }
});

app.get(/.*/, function(req, res){
  var url = req.url.substring(1);
  mongoClient.connect(mongodb, function(err, db){
    findShortened(db, url, function(callback){
      if(callback.length != 0){

   });
  });
  //res.send(url);
});

app.listen(port);

console.log('Server running on http://%s:%s', ip, port);

module.exports = app;


var addDocument = function(db, document, callback) {
    var collection = db.collection('shorturls');
    collection.insertOne(document, function(err, result) {
        console.log("inserted one document");
        callback();
    });
};

var findShortened = function(db, url, callback) {
    var collection = db.collection('shorturls');
    collection.find({
        "shortened": url
    }).toArray(function(err, docs) {
        assert.equal(err, null);
        console.log(docs);
        callback(docs);
    });
}

var findUrl = function(db, url, callback) {
    var collection = db.collection('shorturls');
    collection.find({
        "url": url
    }).toArray(function(err, docs) {
        assert.equal(err, null);
        callback(docs);
    });
}

String.prototype.hashCode = function() {
    var hash = 0,
        i, chr, len;
    if (this.length === 0) return hash;
    for (i = 0, len = this.length; i < len; i++) {
        chr = this.charCodeAt(i);
        hash = ((hash << 5) - hash) + chr;
        hash |= 0; // Convert to 32bit integer
    }
    return hash;
};

        res.redirect(callback[0].url);
      }
 