var express =  require("express");
var router = express.Router();
var db = require("../database/mongo");
var request =  require("request");
var parser = require('xml2json');
var crypto = require("crypto");
//const WolframAlphaAPI = require('./lib/WolframAlphaAPI');

router.get("/solve2/:equation",function(req,res,next){
    var question = req.params.equation;
    console.log(question);
    var dt = new Date();
    var month = ("0" + (dt.getMonth() + 1)).substr(-2);
    var currentmonth = dt.getFullYear() + "-" + month;
    

    db.apiusage.find({month:currentmonth}).sort({usage:1}).limit(1,function(err,data){
        if(!err)
        {
            if(data.length > 0)
            {
                var appid = data[0].appid;
                var theusage = data[0].usage;
                console.log(appid);
                
                var result = {};
                result.steps = [];
                
                  //equation = "x^2";
                //var res = encodeURI(equation);
                var url = "http://api.wolframalpha.com/v2/query?appid="+appid+"&input=solve+"+encodeURIComponent(question)+"&podstate=Result__Step-by-step+solution";
                //console.log(url);
                request(url, function(weberr, resp, body) {
                    //res.send(url);
                    if(!weberr)
                    {      
                        var json = parser.toJson(body);     
                        var address_data = JSON.parse(json);             

                        console.log(address_data.queryresult);
                        var result = [];
                        if(address_data.queryresult.success == "true")
                        {
                            var num =  address_data.queryresult.numpods;
                            var pods = address_data.queryresult.pod;
                            
                            for(i = 0;i<num;i++)
                            {
                                console.log("_______________________________");
                                console.log(pods[i]);
                                if(pods[i].title != "")
                                {
                                    result.push("<h2>"+pods[i].title+ "</h2>");
                                    var numsubpods = pods[i].numsubpods;
                                    for(j = 0;j<numsubpods;j++)
                                    {
                                        if(numsubpods==1)
                                        {
                                            var subpod = pods[i].subpod;                                            
                                        }
                                        else{
                                            var subpod = pods[i].subpod[j];
                                            //result.push("<img src='"+subpod.img.src+"' alt='"+subpod.img.alt+"'>");
                                        }
                                        result.push("<img src='"+subpod.img.src+"' alt='"+subpod.img.alt+"'>");
                                        
                                    }
                                }
                                console.log("_______________________________");
                            }
                        }
                        var resls = JSON.stringify(result);
                        res.send("resultCall("+resls+")");      
                      

                        var query = {};
                        query.month = currentmonth;
                        query.appid =  appid;
                        theusage = theusage + 2;
                        db.apiusage.update(query,{$set:{usage:theusage}});                          
                        //res.send(result);
                        
                    }
                });

            }
        }
        else{
            console.log(err);
        }
    });

});

router.get("/gettopics/:id",function(req,res,next){
    var id = req.params.id;
    console.log(id);
    var query = {};
    query.parent_id = parseInt(id);
    //; //making sure the vid
    console.log(query);
    //db.khanitems.find(query,{pk:1,title:1,kind:1,youtube_id:1},function(err,data){
    db.khanitems.find({parent_id:parseInt(id),processed:{$ne:0},active:1},{pk:1,title:1,kind:1,youtube_id:1},function(err,data){
    
        if(!err)
        {
            if(data.length <1)
            {
                db.khanitems.update({pk:parseInt(id),youtube_id:null},{$set:{active:0}});
            }
            console.log(data);
            var resls = JSON.stringify(data);
            res.send("resultCall("+resls+")");   
             
        }
        else{
            console.log(err);
            res.send("resultCall([])");    
        }
    })

});

router.get("/register/:username/:email/:password",function(req,res,next){
    var username = req.params.username;
    var _email = req.params.email;
    var password = req.params.password;

    db.users.find({email:_email},function(err,data){
        if(!err)
        {
            if(data.length < 1)
            {
                var _user = {};
              _user.name = username;
              _user.surname = password;
              _user.email = _email;
              _user.facebookid= "-1";
              _user.usercode = username.substring(0,2).toUpperCase()+crypto.randomBytes(3).toString("hex").toUpperCase();
              db.users.insert(_user);
              var resls = JSON.stringify(_user);
              res.send("resultCall("+resls+")"); 
              
            }
        }
    })
});

module.exports = router;

