var helpers = require('../helpers'),
    fs = require('fs'),
    path = require('path'),
    itemManager = require('../item-manager'),
    logger = require('../logger')(),
    jobs_manager = require('../job-manager'),
    _ = require ('underscore'),
    generalConfigManager = require('../config-manager')(),
    scheduler = require('../scheduler').scheduler;

function getSafeItemName (item_name){
  return path.basename(item_name).split('.')[0];
}

function getDashboardsFolder(packagesPath) {
  return packagesPath[0] + '\\default\\dashboards\\'
}

function getDashboardConfiguration(packagesPath,dashboardName) {
  return getDashboardsFolder(packagesPath) + dashboardName +".json"; 
}


module.exports = {

    // ---------------------------------------------------------------
    // Create a new dashboard with the default configuration and the entered password.
    // ---------------------------------------------------------------
    createDashboard : function (packagesPath, req, res){
      var dashboardFolder = getDashboardsFolder(packagesPath);
      var name = req.body.name;
      var password = req.body.password;

      var newDashboard =  dashboardFolder + name + ".json";

      if (fs.existsSync(newDashboard)){
          return res.status(500).send('Dashboard "'+ name +'" already exists.');
      }

      var dashboardConfiguration =   _.clone(emptyDashboard);
      dashboardConfiguration.password = password;

      fs.writeFile(newDashboard, JSON.stringify(dashboardConfiguration, null, 4),function(err) {
            if(err) return res.status(500).send(err);
            res.redirect("/"+name);
       });


    },


    // ---------------------------------------------------------------
    // Add a new widget. Schedule the related job.
    // ---------------------------------------------------------------
    addWidget : function (packagesPath, dashboardName, req, res){
         var exclude = ["widget","job"];

         var widgetDefault = generalConfigManager.get('widgets')[req.body.widget];

         readDashboardConfiguration(packagesPath,dashboardName,function(err,dashboard,dasboardConfiguration) {


          if(err) return res.status(500).send(err);


          var widget = {
                row: 1,
                col: 1,
                width: widgetDefault.width,
                height:  widgetDefault.height,
                widget: req.body.widget,
                job: req.body.job,
                config: req.body.widget
            };

          dasboardConfiguration.layout.widgets.push(widget);

          var config = {};
 

          for(prop in req.body) {
            if(exclude.indexOf(prop) == -1){ 

              var value = req.body[prop];
              if(isNumber(value)) {
                config[prop] = parseInt(value);
              } else {
                config[prop] = value;
              }
            }
          }

          dasboardConfiguration.config[req.body.widget] = config;


          fs.writeFileSync(dashboard, JSON.stringify(dasboardConfiguration, null, 4),"utf8");

          jobs_manager.get_job(packagesPath,dashboardName,widget.job, function(err,job) {
              scheduler.scheduleFirst(job,false);
          });
        
          res.redirect('/' + dashboardName);
        });
      },

          // ---------------------------------------------------------------
    // Add a new widget. Schedule the related job.
    // ---------------------------------------------------------------
    deleteWidget : function (packagesPath, dashboardName, widgetId,req, res){
      readDashboardConfiguration(packagesPath,dashboardName,function(err,dashboard,dasboardConfiguration) {

          if(err) return res.status(500).send(err);


          dasboardConfiguration.layout.widgets = _.filter(dasboardConfiguration.layout.widgets, function(widget){ console.log(widget.widget !== widgetId); return widget.widget !== widgetId });
          delete dasboardConfiguration.config[widgetId];

          fs.writeFileSync(dashboard, JSON.stringify(dasboardConfiguration, null, 4),"utf8");

          // Unschedule job.
          scheduler.removeJob(widgetId);

          res.send(200);
        });
      },

      listWidgets: function (packagesPath, dashboardName,req, res){
        readDashboardConfiguration(packagesPath,dashboardName,function(err,dashboard,dasboardConfiguration) {
          
          var widgets = _.clone(generalConfigManager.get('widgets'));

          dasboardConfiguration.layout.widgets.forEach(function(widget) {
              delete widgets[widget.widget];
          });

          res.json(widgets);

        });

      },

      // ---------------------------------------------------------------
      // Return the JSON configuration for a widget
      // ---------------------------------------------------------------
      getWidgetConfig: function (localPackagesPath,dashboardName, widget, req, res){
        var widgetDefaultConfig = generalConfigManager.get('widgets')[widget].config;

        itemManager.get_first(localPackagesPath, dashboardName, "dashboards", ".json", function(err, dashboard){
          if (err || !dashboard){
            return res.send(err ? 400 : 404, err ? err : "Trying to render dashboard " + dashboardName + ", but couldn't find any dashboard in the packages folder");
          }
          var jsonBody;
          try {
            jsonBody = JSON.parse(fs.readFileSync(dashboard));
          }
          catch(e){
            return res.send(400, "Invalid dashboard config file");
          }

          var config = jsonBody.config[widget];
          

          for(prop in config) {
            widgetDefaultConfig[prop].value = config[prop];
          }

          res.json(widgetDefaultConfig);
        });
      },


      // ---------------------------------------------------------------
      // Return the JSON configuration for a widget
      // ---------------------------------------------------------------
      saveWidgetConfig: function (localPackagesPath,dashboardName, widget, req, res){

        itemManager.get_first(localPackagesPath, dashboardName, "dashboards", ".json", function(err, dashboard){
          if (err || !dashboard){
            return res.send(err ? 400 : 404, err ? err : "Trying to render dashboard " + dashboardName + ", but couldn't find any dashboard in the packages folder");
          }
          var jsonBody;
          try {
            jsonBody = JSON.parse(fs.readFileSync(dashboard));
          }
          catch(e){
            return res.send(400, "Invalid dashboard config file");
          }

          jsonBody.config[widget]= req.body;

          fs.writeFileSync(dashboard, JSON.stringify(jsonBody, null, 4));

          // Should be config on not widget
          scheduler.updateConfig(widget,req.body);

          res.send(200);
        });
      },
};


function readDashboardConfiguration(localPackagesPath, dashboardName, cb) {
  var dashboard = getDashboardConfiguration(localPackagesPath,dashboardName);

      if (!dashboard){
        return cb("The configuration of the dashboard " + dashboardName + " couldn't be found.");
      }
      var jsonBody;
      try {
       return  cb(null,dashboard,JSON.parse(fs.readFileSync(dashboard,"utf8")));
      }    catch(e){
        return cb("Invalid dashboard config file");
      }
}

function isNumber(str) {
   var pattern = /^\d+$/;
   return pattern.test(str);  // returns a boolean
}


var emptyDashboard= {
    "layout": {
        "title": false,
        "customJS": [
            "jquery.peity.js",
            "pretty.js",
            "highcharts.js",
            "themes/dark-unica.js"
        ],
        "widgets": []
    },
    "config": {}
};