/**
 * Main command to load configuration by given environment argument
 * and start application server to listen the exposed endpoints and
 * provide the requested resources operations
 *
 * Mandatory parameters are path (/tmp...) and environment (dev, qa, pre, pro...)
 */
func main() {

	// Load configuration to start application
	conf_path, env := checkParams(os.Args)
	var filename = conf_path + "/" + env + ".yml"
	config = configuration.LoadConfiguration(filename)
	log = configuration.GetLog()
	dataservice.Initialize(config)
	log.Infof("dynamic-pricing started with environment: %s and listening in port: %v\n", env, config.Server_port)

	// Register to Eureka and then set up to only heartbeat one of them
	filename = conf_path + "/eureka_" + env + ".gcfg"
	//	ec, i := registerToEureka( filename )
	//	go sendHeartBeatToEureka( ec, i )

	// Create the router to handle requests
	router := mux.NewRouter().StrictSlash(true)
	router.HandleFunc("/dynamic-pricing-api/1.0/prices/{id}", controller.PricesController) // Prices endpoint
	router.HandleFunc("/dynamic-pricing-api/1.0/prices", controller.PricesController)      // Prices endpoint
	router.HandleFunc("/dynamic-pricing-api/1.0/sales/{id}", controller.SalesController)   // Sales endpoint
	router.HandleFunc("/dynamic-pricing-api/1.0/sales", controller.SalesController)        // Sales endpoint
	router.HandleFunc("/dynamic-pricing-api/1.0/info", controller.InfoController)
	router.HandleFunc("/dynamic-pricing-api/1.0/health", controller.HealthController)
	router.HandleFunc("/dynamic-pricing-api/1.0/reload-restrictions", controller.ReloadRestrictionsController)

	// Starting server on given port number
	log.Fatal(http.ListenAndServe(":"+config.Server_port, router)) // Start the server at listening port

}
)

// Parameters response struct
type ParametersResponseType struct {
	StartDate string `json:"start_date"`
	EndDate   string `json:"end_date"`
	EventId   int    `json:event_id`
	SaleId    string `json:"sale_id"`
	Page      int    `json:"page"`
	PageSize  int    `json:"page_size"`
	TraceId   string `json:"trace_id"`
}

// Global vars and default values
var (
	log       *logging.Logger = configuration.GetLog()
	startDate string
	endDate   string
	eventId   int
	config    = configuration.GetConfig()
)

// https://blog.golang.org/context/userip/userip.go
// Funtion to retrieve the sender IP from request
// or from forwared headers instead
func getIP(w http.ResponseWriter, req *http.Request) string {

	ip, _, err := net.SplitHostPort(req.RemoteAddr)
	if err != nil {
		log.Debugf("userip: %q is not IP:port", req.RemoteAddr)
	}