package openapi

import (
	"encoding/json"
	"net/http"
	"strings"

	"github.com/gorilla/mux"
)

type ConsoleApiController struct {
	service ConsoleApiServicer
	errorHandler ErrorHandler
}

type ConsoleApiOption func(*ConsoleApiController)

func WithConsoleApiErrorHandler(h ErrorHandler) ConsoleApiOption {
	return func(c *ConsoleApiController) {
		c.errorHandler = h
	}
}

func NewConsoleApiController(s ConsoleApiServicer, opts ...ConsoleApiOption) Router {
	controller := &ConsoleApiController{
		service:      s,
		errorHandler: DefaultErrorHandler,
	}

	for _, opt := range opts {
		opt(controller)
	}

	return controller
}

func (c *ConsoleApiController) Routes() Routes {
	return Routes{ 
		{
			"GetAemProductInfo",
			strings.ToUpper("Get"),
			"/system/console/status-productinfo.json",
			c.GetAemProductInfo,
		},
		{
			"GetBundleInfo",
			strings.ToUpper("Get"),
			"/system/console/bundles/{name}.json",
			c.GetBundleInfo,
		},
		{
			"GetConfigMgr",
			strings.ToUpper("Get"),
			"/system/console/configMgr",
			c.GetConfigMgr,
		},
		{
			"PostBundle",
			strings.ToUpper("Post"),
			"/system/console/bundles/{name}",
			c.PostBundle,
		},
		{
			"PostJmxRepository",
			strings.ToUpper("Post"),
			"/system/console/jmx/com.adobe.granite:type=Repository/op/{action}",
			c.PostJmxRepository,
		},
		{
			"PostSamlConfiguration",
			strings.ToUpper("Post"),
			"/system/console/configMgr/com.adobe.granite.auth.saml.SamlAuthenticationHandler",
			c.PostSamlConfiguration,
		},
	}
}

func (c *ConsoleApiController) GetAemProductInfo(w http.ResponseWriter, r *http.Request) {
	result, err := c.service.GetAemProductInfo(r.Context())

	if err != nil {
		c.errorHandler(w, r, err, &result)
		return
	}

	EncodeJSONResponse(result.Body, &result.Code, w)

}

func (c *ConsoleApiController) GetBundleInfo(w http.ResponseWriter, r *http.Request) {
	params := mux.Vars(r)
	name := params["name"]

	result, err := c.service.GetBundleInfo(r.Context(), name)

	if err != nil {
		c.errorHandler(w, r, err, &result)
		return
	}

	EncodeJSONResponse(result.Body, &result.Code, w)

}

func (c *ConsoleApiController) GetConfigMgr(w http.ResponseWriter, r *http.Request) {
	result, err := c.service.GetConfigMgr(r.Context())

	if err != nil {
		c.errorHandler(w, r, err, &result)
		return
	}

	EncodeJSONResponse(result.Body, &result.Code, w)

}

func (c *ConsoleApiController) PostBundle(w http.ResponseWriter, r *http.Request) {
	params := mux.Vars(r)
	query := r.URL.Query()
	name := params["name"]

	action := query.Get("action")
	result, err := c.service.PostBundle(r.Context(), name, action)

	if err != nil {
		c.errorHandler(w, r, err, &result)
		return
	}

	EncodeJSONResponse(result.Body, &result.Code, w)

}

func (c *ConsoleApiController) PostJmxRepository(w http.ResponseWriter, r *http.Request) {
	params := mux.Vars(r)
	action := params["action"]

	result, err := c.service.PostJmxRepository(r.Context(), action)

	if err != nil {
		c.errorHandler(w, r, err, &result)
		return
	}

	EncodeJSONResponse(result.Body, &result.Code, w)

}

func (c *ConsoleApiController) PostSamlConfiguration(w http.ResponseWriter, r *http.Request) {
	query := r.URL.Query()
	post, err := parseBoolParameter(query.Get("post"))
	if err != nil {
		w.WriteHeader(500)
		return
	}
	apply, err := parseBoolParameter(query.Get("apply"))
	if err != nil {
		w.WriteHeader(500)
		return
	}
	delete, err := parseBoolParameter(query.Get("delete"))
	if err != nil {
		w.WriteHeader(500)
		return
	}
	action := query.Get("action")
	location := query.Get("$location")
	path := strings.Split(query.Get("path"), ",")
	serviceRanking, err := parseInt32Parameter(query.Get("service.ranking"), false)
	if err != nil {
		c.errorHandler(w, r, &ParsingError{Err: err}, nil)
		return
	}
	idpUrl := query.Get("idpUrl")
	idpCertAlias := query.Get("idpCertAlias")
	idpHttpRedirect, err := parseBoolParameter(query.Get("idpHttpRedirect"))
	if err != nil {
		w.WriteHeader(500)
		return
	}
	serviceProviderEntityId := query.Get("serviceProviderEntityId")
	assertionConsumerServiceURL := query.Get("assertionConsumerServiceURL")
	spPrivateKeyAlias := query.Get("spPrivateKeyAlias")
	keyStorePassword := query.Get("keyStorePassword")
	defaultRedirectUrl := query.Get("defaultRedirectUrl")
	userIDAttribute := query.Get("userIDAttribute")
	useEncryption, err := parseBoolParameter(query.Get("useEncryption"))
	if err != nil {
		w.WriteHeader(500)
		return
	}
	createUser, err := parseBoolParameter(query.Get("createUser"))
	if err != nil {
		w.WriteHeader(500)
		return
	}
	addGroupMemberships, err := parseBoolParameter(query.Get("addGroupMemberships"))
	if err != nil {
		w.WriteHeader(500)
		return
	}
	groupMembershipAttribute := query.Get("groupMembershipAttribute")
	defaultGroups := strings.Split(query.Get("defaultGroups"), ",")
	nameIdFormat := query.Get("nameIdFormat")
	synchronizeAttributes := strings.Split(query.Get("synchronizeAttributes"), ",")
	handleLogout, err := parseBoolParameter(query.Get("handleLogout"))
	if err != nil {
		w.WriteHeader(500)
		return
	}
	logoutUrl := query.Get("logoutUrl")
	clockTolerance, err := parseInt32Parameter(query.Get("clockTolerance"), false)
	if err != nil {
		c.errorHandler(w, r, &ParsingError{Err: err}, nil)
		return
	}
	digestMethod := query.Get("digestMethod")
	signatureMethod := query.Get("signatureMethod")
	userIntermediatePath := query.Get("userIntermediatePath")
	propertylist := strings.Split(query.Get("propertylist"), ",")
	result, err := c.service.PostSamlConfiguration(r.Context(), post, apply, delete, action, location, path, serviceRanking, idpUrl, idpCertAlias, idpHttpRedirect, serviceProviderEntityId, assertionConsumerServiceURL, spPrivateKeyAlias, keyStorePassword, defaultRedirectUrl, userIDAttribute, useEncryption, createUser, addGroupMemberships, groupMembershipAttribute, defaultGroups, nameIdFormat, synchronizeAttributes, handleLogout, logoutUrl, clockTolerance, digestMethod, signatureMethod, userIntermediatePath, propertylist)

	if err != nil {
		c.errorHandler(w, r, err, &result)
		return
	}

	EncodeJSONResponse(result.Body, &result.Code, w)

}
/*
 * Adobe Experience Manager (AEM) API
 *
 * Swagger AEM is an OpenAPI specification for Adobe Experience Manager (AEM) API
 *
 * API version: 3.5.0-pre.0
 * Contact: opensource@shinesolutions.com
 * Generated by: OpenAPI Generator (https://openapi-generator.tech)
 */

package openapi

import (
	"encoding/json"
	"net/http"
	"strings"

	"github.com/gorilla/mux"
)

// ConsoleApiController binds http requests to an api service and writes the service results to the http response
type ConsoleApiController struct {
	service ConsoleApiServicer
	errorHandler ErrorHandler
}

// ConsoleApiOption for how the controller is set up.
type ConsoleApiOption func(*ConsoleApiController)

// WithConsoleApiErrorHandler inject ErrorHandler into controller
func WithConsoleApiErrorHandler(h ErrorHandler) ConsoleApiOption {
	return func(c *ConsoleApiController) {
		c.errorHandler = h
	}
}

// NewConsoleApiController creates a default api controller
func NewConsoleApiController(s ConsoleApiServicer, opts ...ConsoleApiOption) Router {
	controller := &ConsoleApiController{
		service:      s,
		errorHandler: DefaultErrorHandler,
	}

	for _, opt := range opts {
		opt(controller)
	}

	return controller
}

// Routes returns all of the api route for the ConsoleApiController
func (c *ConsoleApiController) Routes() Routes {
	return Routes{ 
		{
			"GetAemProductInfo",
			strings.ToUpper("Get"),
			"/system/console/status-productinfo.json",
			c.GetAemProductInfo,
		},
		{
			"GetBundleInfo",
			strings.ToUpper("Get"),
			"/system/console/bundles/{name}.json",
			c.GetBundleInfo,
		},
		{
			"GetConfigMgr",
			strings.ToUpper("Get"),
			"/system/console/configMgr",
			c.GetConfigMgr,
		},
		{
			"PostBundle",
			strings.ToUpper("Post"),
			"/system/console/bundles/{name}",
			c.PostBundle,
		},
		{
			"PostJmxRepository",
			strings.ToUpper("Post"),
			"/system/console/jmx/com.adobe.granite:type=Repository/op/{action}",
			c.PostJmxRepository,
		},
		{
			"PostSamlConfiguration",
			strings.ToUpper("Post"),
			"/system/console/configMgr/com.adobe.granite.auth.saml.SamlAuthenticationHandler",
			c.PostSamlConfiguration,
		},
	}
}

// GetAemProductInfo - 
func (c *ConsoleApiController) GetAemProductInfo(w http.ResponseWriter, r *http.Request) {
	result, err := c.service.GetAemProductInfo(r.Context())
	// If an error occurred, encode the error with the status code
	if err != nil {
		c.errorHandler(w, r, err, &result)
		return
	}
	// If no error, encode the body and the result code
	EncodeJSONResponse(result.Body, &result.Code, w)

}

// GetBundleInfo - 
func (c *ConsoleApiController) GetBundleInfo(w http.ResponseWriter, r *http.Request) {
	params := mux.Vars(r)
	name := params["name"]
	
	result, err := c.service.GetBundleInfo(r.Context(), name)
	// If an error occurred, encode the error with the status code
	if err != nil {
		c.errorHandler(w, r, err, &result)
		return
	}
	// If no error, encode the body and the result code
	EncodeJSONResponse(result.Body, &result.Code, w)

}

// GetConfigMgr - 
func (c *ConsoleApiController) GetConfigMgr(w http.ResponseWriter, r *http.Request) {
	result, err := c.service.GetConfigMgr(r.Context())
	// If an error occurred, encode the error with the status code
	if err != nil {
		c.errorHandler(w, r, err, &result)
		return
	}
	// If no error, encode the body and the result code
	EncodeJSONResponse(result.Body, &result.Code, w)

}

// PostBundle - 
func (c *ConsoleApiController) PostBundle(w http.ResponseWriter, r *http.Request) {
	params := mux.Vars(r)
	query := r.URL.Query()
	name := params["name"]
	
	action := query.Get("action")
	result, err := c.service.PostBundle(r.Context(), name, action)
	// If an error occurred, encode the error with the status code
	if err != nil {
		c.errorHandler(w, r, err, &result)
		return
	}
	// If no error, encode the body and the result code
	EncodeJSONResponse(result.Body, &result.Code, w)

}

// PostJmxRepository - 
func (c *ConsoleApiController) PostJmxRepository(w http.ResponseWriter, r *http.Request) {
	params := mux.Vars(r)
	action := params["action"]
	
	result, err := c.service.PostJmxRepository(r.Context(), action)
	// If an error occurred, encode the error with the status code
	if err != nil {
		c.errorHandler(w, r, err, &result)
		return
	}
	// If no error, encode the body and the result code
	EncodeJSONResponse(result.Body, &result.Code, w)

}

// PostSamlConfiguration - 
func (c *ConsoleApiController) PostSamlConfiguration(w http.ResponseWriter, r *http.Request) {
	query := r.URL.Query()
	post, err := parseBoolParameter(query.Get("post"))
	if err != nil {
		w.WriteHeader(500)
		return
	}
	apply, err := parseBoolParameter(query.Get("apply"))
	if err != nil {
		w.WriteHeader(500)
		return
	}
	delete, err := parseBoolParameter(query.Get("delete"))
	if err != nil {
		w.WriteHeader(500)
		return
	}
	action := query.Get("action")
	location := query.Get("$location")
	path := strings.Split(query.Get("path"), ",")
	serviceRanking, err := parseInt32Parameter(query.Get("service.ranking"), false)
	if err != nil {
		c.errorHandler(w, r, &ParsingError{Err: err}, nil)
		return
	}
	idpUrl := query.Get("idpUrl")
	idpCertAlias := query.Get("idpCertAlias")
	idpHttpRedirect, err := parseBoolParameter(query.Get("idpHttpRedirect"))
	if err != nil {
		w.WriteHeader(500)
		return
	}
	serviceProviderEntityId := query.Get("serviceProviderEntityId")
	assertionConsumerServiceURL := query.Get("assertionConsumerServiceURL")
	spPrivateKeyAlias := query.Get("spPrivateKeyAlias")
	keyStorePassword := query.Get("keyStorePassword")
	defaultRedirectUrl := query.Get("defaultRedirectUrl")
	userIDAttribute := query.Get("userIDAttribute")
	useEncryption, err := parseBoolParameter(query.Get("useEncryption"))
	if err != nil {
		w.WriteHeader(500)
		return
	}
	createUser, err := parseBoolParameter(query.Get("createUser"))
	if err != nil {
		w.WriteHeader(500)
		return
	}
	addGroupMemberships, err := parseBoolParameter(query.Get("addGroupMemberships"))
	if err != nil {
		w.WriteHeader(500)
		return
	}
	groupMembershipAttribute := query.Get("groupMembershipAttribute")
	defaultGroups := strings.Split(query.Get("defaultGroups"), ",")
	nameIdFormat := query.Get("nameIdFormat")
	synchronizeAttributes := strings.Split(query.Get("synchronizeAttributes"), ",")
	handleLogout, err := parseBoolParameter(query.Get("handleLogout"))
	if err != nil {
		w.WriteHeader(500)
		return
	}
	logoutUrl := query.Get("logoutUrl")
	clockTolerance, err := parseInt32Parameter(query.Get("clockTolerance"), false)
	if err != nil {
		c.errorHandler(w, r, &ParsingError{Err: err}, nil)
		return
	}
	digestMethod := query.Get("digestMethod")
	signatureMethod := query.Get("signatureMethod")
	userIntermediatePath := query.Get("userIntermediatePath")
	propertylist := strings.Split(query.Get("propertylist"), ",")
	result, err := c.service.PostSamlConfiguration(r.Context(), post, apply, delete, action, location, path, serviceRanking, idpUrl, idpCertAlias, idpHttpRedirect, serviceProviderEntityId, assertionConsumerServiceURL, spPrivateKeyAlias, keyStorePassword, defaultRedirectUrl, userIDAttribute, useEncryption, createUser, addGroupMemberships, groupMembershipAttribute, defaultGroups, nameIdFormat, synchronizeAttributes, handleLogout, logoutUrl, clockTolerance, digestMethod, signatureMethod, userIntermediatePath, propertylist)
	// If an error occurred, encode the error with the status code
	if err != nil {
		c.errorHandler(w, r, err, &result)
		return
	}
	// If no error, encode the body and the result code
	EncodeJSONResponse(result.Body, &result.Code, w)

}
