var cli = require("./3scale-cli");
var config = require("./config");
var parser = require("raml-1-parser");
var Q = require("q");
var slugify = require("slugify");
var _ = require("underscore");

var services = require("./services");
var appplan = require("./application_plans");
var metrics = require("./metrics");
var methods = require("./methods");

var METHOD_ARR=[]

exports.import = function(path, service_id, appplan_name){
  var api = parser.loadApiSync(path);
  var title = api.title()+Math.floor((Math.random() * 50) + 10);
  api.resourceTypes().forEach(function(type){
    console.log(type.name() + " : " + type.kind());
  })
  console.log(api.resourceTypes()[0].methods().length)

  cli.print({message: "Loading "+title+ " raml definition."});

  if(service_id){ //update existing service
    console.log(service_id);
    threescale_waterfall(api, service_id,appplan_name);
  }else{
    var ser = services.createService(title).then(function(s){
      var service_id = s.service.id;
      cli.print({message: "Service with id "+ service_id+" created on 3scale"});
      threescale_waterfall(api, service_id, appplan_name);
   });
 }
}

var  threescale_waterfall= function(api, service_id, appplan_name){
  appplan.getPlan(service_id,appplan_name).then(function(plan){
    console.log(plan)
    if(plan)
      return;
    return appplan.createAppPlan(service_id,appplan_name).then(function(plan){
        var application_plan_id = plan.application_plan.id;
        cli.print({message: "Application plan with id "+ application_plan_id+" created on 3scale"});
    })
  })
  // appplan.createAppPlan(service_id,appplan_name).then(function(plan){
  //   var application_plan_id = plan.application_plan.id;
  //   cli.print({message: "Application plan with id "+ application_plan_id+" created on 3scale"});
  // })
  .then(function(){
    return metrics.listMetrics(service_id);
  })
  .then(function(metricList){
    cli.print({message: "Hits metric with id "+ metricList.metrics[0].metric.id+" found on 3scale"});
    HIT_METRIC_ID = metricList.metrics[0].metric.id;
    return metricList.metrics[0].metric.id;
  }).then(function(hit_metric_id){
    var methodsArr = [];
    console.log(api.title())
    var methodsArr = [];
    var apiResources = api.resources();

    // apiResources.forEach(function(r){
    //   console.log("HEREddd")
    //   exploreResource(r);
    // })
    var promises = [];
    for (var i =0; i<apiResources.length;i++) {
      console.log(apiResources[i].absoluteUri());
      promises.push(exploreResource(apiResources[i])); // push the Promises to our array
    }
    return Q.all(promises);
    //  return METHOD_ARR;
  }).then(function(methodsArr){
    console.log("HERE",methodsArr)
    var promisesArr = [];
    methodsArr.forEach(function(m){
      promisesArr.push(methods.createMethod(service_id,HIT_METRIC_ID,m.system_name,m.friendly_name).then(function(data){
        cli.print({message:"Method "+data.name+" with system_name "+data.system_name+" created on 3scale."});
        }));
    });
    return Q.all(promisesArr); //aray of promises
 }).then(function(a){
    cli.success({message:"Import on 3scale complete"});
 }).done();
};


var exploreResource = function(resource){
  console.log("called")
  var arr = []
  var methods = resource.methods()
  // console.log("nb methods",methods.length,methods)

  if(resource.resources().length>0){
    var promises = [];
    var apiResources = resource.resources()
    for (var i =0; i<apiResources.length;i++) {
      promises.push(exploreResource(apiResources[i])); // push the Promises to our array
    }
    Q.all(promises);
  }else{
    console.log("AAA",resource.absoluteUri());

    console.log(resource.type().kind())
    METHOD_ARR = _.union(METHOD_ARR,exploreMethods(resource.methods()))
    console.log(METHOD_ARR);
  }


 //  return Q.fcall(exploreMethods(methods))
 //  .then(function(){
 //    // console.log("met",met)
 //    // arr = _.union(arr,met)
 //    return arr
 // }).then(function(){
 //   if(resource.resources().length>0){
 //     var promises = [];
 //     var apiResource = resource.resources()
 //     for (var r in apiResources) {
 //       promises.push(exploreResource(r)); // push the Promises to our array
 //     }
 //     return Q.all(promises);
 //   }else{
 //     return true
 //   }
 // });

  return true;
  //add methods
  //if more resources, recursive on ressources
 //  var arr = []
 //  var methods = resource.methods()
 //  exploreMethods(methods).then(function(met){
 //    console.log("met",met)
 //      arr = _.union(arr,met)
 //  })
 // // on root
 //  if(resource.resources().length>0){
 //    var promises = methods.map(function (r){exploreResource(r); return r})
 //    return Q.all(promises)
 //    // return Q.all(resource.resources().map(function(r){
 //    //   exploreResource(r);
 //    // }))
 //    // return resource.resources().forEach(function(r){
 //    //   exploreResource(r);
 //    // }).then(function(){
 //    //     console.log("DONE EXPLORE")
 //    //     return arr
 //    // });
 //  }
}
var exploreMethods = function(methods){
  var arr = []
  console.log("exmethod called",methods.length)
  return methods;
//   var promises = methods.map(function (m) { console.log(m.method(),m.kind(),m.displayName());
//   var method = {}
//   method.path = resource.absoluteUri();
//   method.method = m.method();
//   method.friendly_name = m.method().toUpperCase()+"_"+resource.absoluteUri(); //GET_/shop/pets
//   method.system_name = m.method().toUpperCase()+"_"+resource.absoluteUri(); //GET_/shop/pets
//   method.system_name = method.system_name.replace("}","_").replace('{',"_")
//   arr.push(method);
// return arr })
//   return Q.all(promises)

  // return Q.all(methods.map(function(m){
  //
  // }))
  //  methods.forEach(function(m){
  //   console.log(m.method(),m.kind(),m.displayName());
  //   var method = {}
  //   method.path = resource.absoluteUri();
  //   method.method = m.method();
  //   method.friendly_name = m.method().toUpperCase()+"_"+resource.absoluteUri(); //GET_/shop/pets
  //   method.system_name = m.method().toUpperCase()+"_"+resource.absoluteUri(); //GET_/shop/pets
  //   method.system_name = method.system_name.replace("}","_").replace('{',"_")
  //   arr.push(method);
  // })
  // .then(function(){
  //   return arr;
  // })
}
