var parser = require("swagger-parser");
var request = require("request");
var slugify = require("slugify");
var qs = require("qs");
var async = require("async");
var PROVIDER_KEY = "da3be4aba4fbcc8267dac7202ee01442";
var SERVICE_ID = "2555417729058"
var APPLICATION_PLAN_ID = "2357355836882"
var METRIC_ID = "2555417932670" //Hits
var API = "https://nico3scale-admin.3scale.net/admin/api"

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

parser.parse("./petstore.json', function(err, api, metadata) {
  if (!err) {
    console.log("API name: %s, Version: %s", api.info.title, api.info.version);
    // createService(api.info.title)
    title = api.info.title;

    async.waterfall([
      function(callback){
        callback(null,title+Math.floor((Math.random() * 50) + 10));
      },
      function (name,createServiceCb){
        var url = API+"/services.json";
        console.log(url);
        var options ={
          url: url,
          form:{
            "provider_key":PROVIDER_KEY,
            "name":name,
            "system_name":slugify(name,"_")
          }
        };
        request.post(options, function(error, response, body){
          console.log("createService",body);
          if(error){
            createServiceCb(error);
          }else {
            var data =  JSON.parse(body);
            if(data.errors)
              createServiceCb(data.errors);

            SERVICE_ID = data.service.id
            createServiceCb(null, data.service.id);
          }
        });
      },
      function(service_id,createApplicationPlanCb){
        var url = API+"/services/"+service_id+"/application_plans.json";
        console.log(url);
        var options ={
          url: url,
          form:{
            "provider_key":PROVIDER_KEY,
            "name":"default",
            "system_name":"default"
          }
        };
        request.post(options, function(error, response, body){
          console.log("application_plan",body);
          if(error){
            createApplicationPlanCb(error);
          }else{
            var data =  JSON.parse(body);
            if(data.errors)
              createApplicationPlanCb(error);

            APPLICATION_PLAN_ID = data.application_plan.id;
            createApplicationPlanCb(null, data.application_plan.id);
          }
        });
      },
      function(arg1,listMetricCb){
        var url = API+"/services/"+SERVICE_ID+"/metrics.json";
        console.log(url);
        var options ={
          url: url,
          form:{
            "provider_key":PROVIDER_KEY,
            "service_id":SERVICE_ID,
          }
        };
        request.get(options, function(error, response, body){
          console.log(body);
          if(error){
            listMetricCb(error);
          }else{
            var data =  JSON.parse(body);
            if(data.errors)
              listMetricCb(error);

            console.log("METRICS_",data);
            METRIC_ID = data.metrics[0].metric.id;
            listMetricCb(null,data.metrics[0].metric.id); //by default first it's hits
          }
        });
      },
      function(metric_id,createMethodCb){
        var methods = [];
        for (var e in api.paths){
          console.log(e,api.paths[e]);
          for(var m in api.paths[e]){ //methods
            console.log(m,api.paths[e][m]);
            var method = api.paths[e][m];
            methods.push(method)
            // createMethod(SERVICE_ID,METRIC_ID,method.operationId,1);
          }
       }
      },
      function(methods,createMethodCb){
        methods.forEach(function(m){
          var url = API+"/services/"+SERVICE_ID+"/metrics/"+METRIC_ID+"/methods.json";
          console.log(url);
          var options ={
            url: url,
            form:{
              "provider_key":PROVIDER_KEY,
              "service_id":SERVICE_ID,
              "metric_id": METRIC_ID,
              "friendly_name":m.operationId,
              "system_name":slugify(m.operationId,"_"),
              "unit":1
            }
          };
          request.post(options, function(error, response, body){
            console.log(body);
            // if(error)
            //   createMethodCb(error);
            // else
            //   createMethodCb(null,body);
          });
        });
      }
    ], function (err, result) {
        // result now equals 'done'
        console.log("done",err,result);
    });

    // console.log(api);
    // console.log(api.paths)
    // console.log(Object.size(api.paths))
    //1. create services
    //2. create application plan
    //3. create metrics
    // createService(api.info.title);
    // createApplicationPlan(SERVICE_ID);
    // for (var e in api.paths){//i = 0, len = Object.size(api.paths);i<len; i++){
    //   console.log(e,api.paths[e]);
    //   for(var m in api.paths[e]){ //methods
    //     console.log(m,api.paths[e][m]);
    //     var method = api.paths[e][m];
    //     createMethod(SERVICE_ID,METRIC_ID,method.operationId,1);
    //   }
    //   // createMethod(SERVICE_ID,METRIC_ID,,1)
    // }
    // listMetric(SERVICE_ID);
  }else{
    console.log(error);
  }
});


var createMethod = function(service_id,metric_id,name,unit,createMethodCb){
  var url = API+"/services/"+service_id+"/metrics/"+metric_id+"/methods.json";
  console.log(url);
  var options ={
    url: url,
    form:{
      "provider_key":PROVIDER_KEY,
      "service_id":service_id,
      "metric_id": metric_id,
      "friendly_name":name,
      "system_name":slugify(name,"_"),
      "unit":unit
    }
  };
  request.post(options, function(error, response, body){
    console.log(body);
    if(error)
      createMethodCb(error);
    else
      createMethodCb(null,body);
  });
};

//1. list metric and find hits id
//2. create methods underneath
var listMetric = function(service_id,listMetricCb){
  var url = API+"/services/"+service_id+"/metrics.json";
  console.log(url);
  var options ={
    url: url,
    form:{
      "provider_key":PROVIDER_KEY,
      "service_id":service_id,
    }
  };
  request.get(options, function(error, response, body){
    console.log(body);
    if(error)
      listMetricCb(error);
    else
      listMetricCb(null,body);
  });
};


var createServiceMetric = function(service_id, friendly_name, system_name,unit,createServiceMetricCb){
  var url = API+"/services/"+service_id+"/metrics.json";
  console.log(url);
  var options ={
    url: url,
    form:{
      "provider_key":PROVIDER_KEY,
      "service_id":service_id,
      "friendly_name":name,
      "system_name":slugify(name,"_"),
      "unit":unit
    }
  };
  request.post(options, function(error, response, body){
    console.log(body);
    if(error)
      createServiceMetricCb(error);
    else
      createServiceMetricCb(null,body);
  });
};

var addFeatureToApplicationPlan = function(applicationplan_id, feature_id){

};

var createServiceFeature = function(service_id,name){
  var url = API+"/services/"+service_id+"/features.json";
  console.log(url);
  var options ={
    url: url,
    form:{
      "provider_key":PROVIDER_KEY,
      "name":nam,
      "system_name":stringify(name,"_"),
      "scope":"ApplicationPlan"
    }
  };
  request.post(options, function(error, response, body){
    console.log(body);
  });
};

var createApplicationPlan = function(service_id,createApplicationPlanCb){
  var url = API+"/services/"+service_id+"/application_plans.json";
  console.log(url);
  var options ={
    url: url,
    form:{
      "provider_key":PROVIDER_KEY,
      "name":"default",
      "system_name":"default"
    }
  };
  request.post(options, function(error, response, body){
    console.log("application_plan",body);
    if(error)
      createApplicationPlanCb(error);
    else
      createApplicationPlanCb(null, JSON.parse(body));
  });
};

var createService = function(name,createServiceCb){
  var url = API+"/services.json";
  console.log(url);
  var options ={
    url: url,
    form:{
      "provider_key":PROVIDER_KEY,
      "name":name,
      "system_name":slugify(name,"_")
    }
  };
  request.post(options, function(error, response, body){
    console.log(body);
    if(error){
      createServiceCb(error);
    }else {
      //return service_id
      createServiceCb(null, JSON.parse(body.service.id));
    }
  });
};


var asyncCall = function(title){
  async.waterfall([
    function (name,createServiceCb){
      var url = API+"/services.json";
      console.log(url);
      var options ={
        url: url,
        form:{
          "provider_key":PROVIDER_KEY,
          "name":name,
          "system_name":slugify(name,"_")
        }
      };
      request.post(options, function(error, response, body){
        console.log(body);
        if(error){
          createServiceCb(error);
        }else {
          //return service_id
          createServiceCb(null, JSON.parse(body).service.id);
        }
      });
    },
    function(service_id,createApplicationPlanCb){
      var url = API+"/services/"+service_id+"/application_plans.json";
      console.log(url);
      var options ={
        url: url,
        form:{
          "provider_key":PROVIDER_KEY,
          "name":"default",
          "system_name":"default"
        }
      };
      request.post(options, function(error, response, body){
        console.log("application_plan",body);
        if(error)
          createApplicationPlanCb(error);
        else
          createApplicationPlanCb(null, JSON.parse(body));
      });
    }
  ], function (err, result) {
      // result now equals 'done'
      console.log(err,result);
  });
}
