// Copyright 2022 Cisco Systems, Inc. and its affiliates
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

/*
 * Flame REST API
 *
 * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
 *
 * API version: 1.0.0
 * Generated by: OpenAPI Generator (https://openapi-generator.tech)
 */

package openapi

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

	"github.com/cisco-open/flame/pkg/openapi/constants"
	"github.com/gorilla/mux"
)

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

// DatasetsApiOption for how the controller is set up.
type DatasetsApiOption func(*DatasetsApiController)

// WithDatasetsApiErrorHandler inject ErrorHandler into controller
func WithDatasetsApiErrorHandler(h ErrorHandler) DatasetsApiOption {
	return func(c *DatasetsApiController) {
		c.errorHandler = h
	}
}

// NewDatasetsApiController creates a default api controller
func NewDatasetsApiController(s DatasetsApiServicer, opts ...DatasetsApiOption) Router {
	controller := &DatasetsApiController{
		service:      s,
		errorHandler: DefaultErrorHandler,
	}

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

	return controller
}

// Routes returns all the api routes for the DatasetsApiController
func (c *DatasetsApiController) Routes() Routes {
	return Routes{
		{
			"CreateDataset",
			strings.ToUpper("Post"),
			"/users/{user}/datasets",
			c.CreateDataset,
		},
		{
			"GetAllDatasets",
			strings.ToUpper("Get"),
			"/datasets",
			c.GetAllDatasets,
		},
		{
			"GetDataset",
			strings.ToUpper("Get"),
			"/users/{user}/datasets/{datasetId}",
			c.GetDataset,
		},
		{
			"GetDatasets",
			strings.ToUpper("Get"),
			"/users/{user}/datasets",
			c.GetDatasets,
		},
		{
			"UpdateDataset",
			strings.ToUpper("Put"),
			"/users/{user}/datasets/{datasetId}",
			c.UpdateDataset,
		},
		{
			"DeleteDataset",
			strings.ToUpper("Delete"),
			"/users/{user}/datasets/{datasetId}",
			c.DeleteDataset,
		},
	}
}

// CreateDataset - Create meta info for a new dataset.
func (c *DatasetsApiController) CreateDataset(w http.ResponseWriter, r *http.Request) {
	params := mux.Vars(r)
	userParam := params[constants.ParamUser]

	datasetInfoParam := DatasetInfo{}
	d := json.NewDecoder(r.Body)
	d.DisallowUnknownFields()
	if err := d.Decode(&datasetInfoParam); err != nil {
		c.errorHandler(w, r, &ParsingError{Err: err}, nil)
		return
	}
	if err := AssertDatasetInfoRequired(datasetInfoParam); err != nil {
		c.errorHandler(w, r, err, nil)
		return
	}
	result, err := c.service.CreateDataset(r.Context(), userParam, datasetInfoParam)
	// 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)
}

// GetAllDatasets - Get the meta info on all the datasets
func (c *DatasetsApiController) GetAllDatasets(w http.ResponseWriter, r *http.Request) {
	query := r.URL.Query()
	limitParam, err := parseInt32Parameter(query.Get(constants.ParamLimit), false)
	if err != nil {
		c.errorHandler(w, r, &ParsingError{Err: err}, nil)
		return
	}
	result, err := c.service.GetAllDatasets(r.Context(), limitParam)
	// 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)
}

// GetDataset - Get dataset meta information
func (c *DatasetsApiController) GetDataset(w http.ResponseWriter, r *http.Request) {
	params := mux.Vars(r)
	userParam := params[constants.ParamUser]

	datasetIdParam := params["datasetId"]

	result, err := c.service.GetDataset(r.Context(), userParam, datasetIdParam)
	// 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)
}

// GetDatasets - Get the meta info on all the datasets owned by user
func (c *DatasetsApiController) GetDatasets(w http.ResponseWriter, r *http.Request) {
	params := mux.Vars(r)
	query := r.URL.Query()
	userParam := params[constants.ParamUser]

	limitParam, err := parseInt32Parameter(query.Get(constants.ParamLimit), false)
	if err != nil {
		c.errorHandler(w, r, &ParsingError{Err: err}, nil)
		return
	}
	result, err := c.service.GetDatasets(r.Context(), userParam, limitParam)
	// 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)
}

// UpdateDataset - Update meta info for a given dataset
func (c *DatasetsApiController) UpdateDataset(w http.ResponseWriter, r *http.Request) {
	params := mux.Vars(r)
	userParam := params[constants.ParamUser]

	datasetIdParam := params["datasetId"]

	datasetInfoParam := DatasetInfo{}
	d := json.NewDecoder(r.Body)
	d.DisallowUnknownFields()
	if err := d.Decode(&datasetInfoParam); err != nil {
		c.errorHandler(w, r, &ParsingError{Err: err}, nil)
		return
	}
	if err := AssertDatasetInfoRequired(datasetInfoParam); err != nil {
		c.errorHandler(w, r, err, nil)
		return
	}
	result, err := c.service.UpdateDataset(r.Context(), userParam, datasetIdParam, datasetInfoParam)
	// 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)
}

func (c *DatasetsApiController) DeleteDataset(w http.ResponseWriter, r *http.Request) {
	params := mux.Vars(r)
	userParam := params[constants.ParamUser]

	datasetIdParam := params[constants.ParamDatasetID]

	result, err := c.service.DeleteDataset(r.Context(), userParam, datasetIdParam)
	// 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)
}
