// 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 controller

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"path"
	"strings"

	"go.uber.org/zap"

	"github.com/cisco-open/flame/cmd/controller/app/database"
	"github.com/cisco-open/flame/pkg/openapi"
	"github.com/cisco-open/flame/pkg/util"
)

// DatasetsApiService is a service that implents the logic for the DatasetsApiServicer
// This service should implement the business logic for every endpoint for the DatasetsApi API.
// Include any external packages or services that will be required by this service.
type DatasetsApiService struct {
	dbService database.DBService
}

// NewDatasetsApiService creates a default api service
func NewDatasetsApiService(dbService database.DBService) openapi.DatasetsApiServicer {
	return &DatasetsApiService{
		dbService: dbService,
	}
}

// CreateDataset - Create meta info for a new dataset.
func (s *DatasetsApiService) CreateDataset(ctx context.Context, user string,
	datasetInfo openapi.DatasetInfo) (openapi.ImplResponse, error) {
	// get datasetRealm field and identify if it is computeId _or_ region
	datasetRealm := datasetInfo.Realm
	datasetInfo.ComputeId = util.DefaultRealm
	isRegion := strings.HasPrefix(datasetRealm, util.DefaultRealm+util.RealmSep)
	// TODO enforce compute registration starting with defaultRealm by pre-pending region.

	// Public dataset: 	The realm may not map correctly to a region or compute. For a valid datasetInfo.Realm, expansion will take place.
	// 					If datasetInfo.Realm represents an invalid region, it is retained (for groupBy) and computeId will be defaultRealm.
	// 					If datasetInfo.Realm represents an invalid computeId, an error is thrown. The assumption is that the user
	// 					specified a computeId for some specific reason(s) and it may not be correct to re-assign it to another cluster.
	// Private dataset: The realm must map to a correct region or registered compute. For a valid datasetInfo.Realm, expansion will take place.

	if isRegion {
		err := s.checkComputeForDatasetByRegion(datasetRealm, &datasetInfo)
		if err != nil {
			return openapi.Response(http.StatusInternalServerError, nil), err
		}
	} else {
		err := s.checkComputeForDatasetByComputeId(datasetRealm, &datasetInfo)
		if err != nil {
			return openapi.Response(http.StatusInternalServerError, nil), err
		}
	}

	zap.S().Infof("after checks for dataset creation, datasetInfo.Realm: %v and datasetInfo.computeId: %v",
		datasetInfo.Realm, datasetInfo.ComputeId)
	datasetId, err := s.dbService.CreateDataset(user, datasetInfo)
	if err != nil {
		return openapi.Response(http.StatusInternalServerError, nil), err
	}

	return openapi.Response(http.StatusCreated, datasetId), nil
}

// GetAllDatasets - Get the meta info on all the datasets
func (s *DatasetsApiService) GetAllDatasets(ctx context.Context, limit int32) (openapi.ImplResponse, error) {
	datasetList, err := s.dbService.GetDatasets("", limit)
	if err != nil {
		return openapi.Response(http.StatusInternalServerError, nil), fmt.Errorf("failed to get list of datasets: %v", err)
	}

	return openapi.Response(http.StatusOK, datasetList), nil
}

// GetDataset - Get dataset meta information
func (s *DatasetsApiService) GetDataset(ctx context.Context, user string, datasetId string) (openapi.ImplResponse, error) {
	// TODO - update GetDataset with the required logic for this service method.
	// Add api_datasets_service.go to the .openapi-generator-ignore to avoid overwriting this service
	// implementation when updating open api generation.

	//TODO: Uncomment the next line to return response Response(200, DatasetInfo{}) or use other options such as http.Ok ...
	//return Response(200, DatasetInfo{}), nil

	//TODO: Uncomment the next line to return response Response(0, Error{}) or use other options such as http.Ok ...
	//return Response(0, Error{}), nil

	return openapi.Response(http.StatusNotImplemented, nil), errors.New("GetDataset method not implemented")
}

// GetDatasets - Get the meta info on all the datasets owned by user
func (s *DatasetsApiService) GetDatasets(ctx context.Context, user string, limit int32) (openapi.ImplResponse, error) {
	datasetList, err := s.dbService.GetDatasets(user, limit)
	if err != nil {
		return openapi.Response(http.StatusInternalServerError, nil), fmt.Errorf("failed to get list of datasets: %v", err)
	}

	return openapi.Response(http.StatusOK, datasetList), nil
}

// UpdateDataset - Update meta info for a given dataset
func (s *DatasetsApiService) UpdateDataset(ctx context.Context, user string, datasetId string,
	datasetInfo openapi.DatasetInfo) (openapi.ImplResponse, error) {
	dataset, err := s.dbService.UpdateDataset(user, datasetId, datasetInfo)
	if err != nil {
		return openapi.Response(http.StatusInternalServerError, nil), err
	}

	return openapi.Response(http.StatusOK, dataset), nil
}

func (s *DatasetsApiService) checkComputeForDatasetByRegion(datasetRealm string, datasetInfo *openapi.DatasetInfo) error {
	eligibleComputes, err := s.dbService.GetComputeIdsByRegion(datasetRealm)
	if len(eligibleComputes) == 0 {
		// No compute found for the given region.
		// If dataset is public, retain the realm within specified in dataset.json. Set compute to DefaultRealm.
		if !datasetInfo.IsPublic {
			errorMsg := fmt.Sprintf("failed to create new private dataset for region: %v, error: %v", datasetRealm, err)
			zap.S().Errorf(errorMsg)
			return fmt.Errorf(errorMsg)
		} else {
			zap.S().Infof("couldnt find compute for public dataset in region %v, assigning defaultRealm", datasetRealm)
			datasetInfo.ComputeId = util.DefaultRealm
		}
	} else {
		// if region is found for public or private dataset, perform realm expansion
		datasetInfo.Realm = path.Join(datasetRealm, eligibleComputes[0])
		datasetInfo.ComputeId = datasetInfo.Realm[strings.LastIndex(datasetInfo.Realm, util.RealmSep)+1:]
		zap.S().Infof("found compute: %s for dataset in region %v", eligibleComputes[0], datasetRealm)
	}
	return nil
}

func (s *DatasetsApiService) checkComputeForDatasetByComputeId(datasetRealm string, datasetInfo *openapi.DatasetInfo) error {
	computeSpec, err := s.dbService.GetComputeById(datasetRealm)
	if err != nil {
		// No compute found for given computeId for public or private dataset. Return an error.
		errorMsg := fmt.Sprintf("computeId %s not found while trying to create new dataset. Err: %v", datasetRealm, err)
		zap.S().Errorf(errorMsg)
		return fmt.Errorf(errorMsg)
	} else {
		// if computeId is found for public or private dataset, perform realm expansion
		datasetInfo.Realm = path.Join(computeSpec.Region, datasetRealm)
		datasetInfo.ComputeId = datasetInfo.Realm[strings.LastIndex(datasetInfo.Realm, util.RealmSep)+1:]
		zap.S().Infof("compute: %s for dataset is valid, region returned: %v", datasetRealm, computeSpec.Region)
	}
	return nil
}

// DeleteDataset - Delete dataset
func (s *DatasetsApiService) DeleteDataset(ctx context.Context, user string, datasetId string) (openapi.ImplResponse, error) {
	zap.S().Debugf("Received DeleteDataset Delete request: %s | %s", user, datasetId)

	err := s.dbService.DeleteDataset(user, datasetId)
	if err != nil {
		return openapi.Response(http.StatusInternalServerError, nil), err
	}

	return openapi.Response(http.StatusOK, nil), nil
}
