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

import (
	"context"
	"fmt"
	"net/http"
	"strconv"

	"go.uber.org/zap"

	"github.com/cisco-open/flame/pkg/openapi"
	"github.com/cisco-open/flame/pkg/openapi/constants"
	"github.com/cisco-open/flame/pkg/restapi"
	"github.com/cisco-open/flame/pkg/util"
)

// JobsApiService is a service that implents the logic for the JobsApiServicer
// This service should implement the business logic for every endpoint for the JobsApi API.
// Include any external packages or services that will be required by this service.
type JobsApiService struct {
}

// NewJobsApiService creates a default api service
func NewJobsApiService() openapi.JobsApiServicer {
	return &JobsApiService{}
}

// CreateJob - Create a new job specification
func (s *JobsApiService) CreateJob(ctx context.Context, user string, jobSpec openapi.JobSpec) (openapi.ImplResponse, error) {
	// TODO: validate the input
	zap.S().Debugf("New job request received for user: %s | jobSpec: %v", user, jobSpec)

	// create controller request
	uriMap := map[string]string{
		constants.ParamUser: user,
	}
	url := restapi.CreateURL(HostEndpoint, restapi.CreateJobEndpoint, uriMap)

	// send post request
	code, body, err := restapi.HTTPPost(url, jobSpec, "application/json")
	errResp, retErr := errorResponse(code, body, err)
	if retErr != nil {
		return errResp, retErr
	}

	// everything went well and response is a job id
	jobStatus := openapi.JobStatus{}
	err = util.ByteToStruct(body, &jobStatus)
	if err != nil {
		errMsg := fmt.Sprintf("failed to construct response message: %v", err)
		zap.S().Errorf(errMsg)
		return openapi.Response(http.StatusInternalServerError, nil), fmt.Errorf(errMsg)
	}

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

// DeleteJob - Delete job specification
func (s *JobsApiService) DeleteJob(ctx context.Context, user string, jobId string) (openapi.ImplResponse, error) {
	zap.S().Debugf("Job delete request received for user: %s | jobId: %v", user, jobId)

	// create controller request
	uriMap := map[string]string{
		constants.ParamUser:  user,
		constants.ParamJobID: jobId,
	}
	url := restapi.CreateURL(HostEndpoint, restapi.DeleteJobEndPoint, uriMap)

	// send put request
	code, body, err := restapi.HTTPDelete(url, jobId, "application/json")
	errResp, retErr := errorResponse(code, body, err)
	if retErr != nil {
		return errResp, retErr
	}

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

// GetJob - Get a job specification
func (s *JobsApiService) GetJob(ctx context.Context, user string, jobId string) (openapi.ImplResponse, error) {
	zap.S().Debugf("Get jobId %s for user: %s", jobId, user)

	//create controller request
	uriMap := map[string]string{
		constants.ParamUser:  user,
		constants.ParamJobID: jobId,
	}
	url := restapi.CreateURL(HostEndpoint, restapi.GetJobEndPoint, uriMap)

	// send get request
	code, body, err := restapi.HTTPGet(url)
	errResp, retErr := errorResponse(code, body, err)
	if retErr != nil {
		return errResp, retErr
	}

	jobSpec := openapi.JobSpec{}
	err = util.ByteToStruct(body, &jobSpec)

	return openapi.Response(http.StatusOK, jobSpec), err
}

// GetJobStatus - Get job status of a given jobId
func (s *JobsApiService) GetJobStatus(ctx context.Context, user string, jobId string) (openapi.ImplResponse, error) {
	zap.S().Debugf("Get jobId %s status for user: %s", jobId, user)

	//create controller request
	uriMap := map[string]string{
		constants.ParamUser:  user,
		constants.ParamJobID: jobId,
	}
	url := restapi.CreateURL(HostEndpoint, restapi.GetJobStatusEndPoint, uriMap)

	// send get request
	code, body, err := restapi.HTTPGet(url)
	errResp, retErr := errorResponse(code, body, err)
	if retErr != nil {
		return errResp, retErr
	}

	jobStatus := openapi.JobStatus{}
	err = util.ByteToStruct(body, &jobStatus)

	return openapi.Response(http.StatusOK, jobStatus), err
}

// GetJobs - Get status info on all the jobs owned by user
func (s *JobsApiService) GetJobs(ctx context.Context, user string, limit int32) (openapi.ImplResponse, error) {
	zap.S().Debugf("Get status of all jobs for user: %s", user)

	//create controller request
	uriMap := map[string]string{
		constants.ParamUser:  user,
		constants.ParamLimit: strconv.Itoa(int(limit)),
	}
	url := restapi.CreateURL(HostEndpoint, restapi.GetJobsEndPoint, uriMap)

	// send get request
	code, body, err := restapi.HTTPGet(url)
	errResp, retErr := errorResponse(code, body, err)
	if retErr != nil {
		return errResp, retErr
	}

	jobStatusList := []openapi.JobStatus{}
	err = util.ByteToStruct(body, &jobStatusList)

	return openapi.Response(http.StatusOK, jobStatusList), err
}

// GetJobsByCompute - Get status info on all the jobs by compute
func (s *JobsApiService) GetJobsByCompute(ctx context.Context, computeId string) (openapi.ImplResponse, error) {
	zap.S().Debugf("Get status of all jobs for compute: %s", computeId)

	//create controller request
	uriMap := map[string]string{
		constants.ParamComputeID: computeId,
	}
	url := restapi.CreateURL(HostEndpoint, restapi.GetJobsByComputeEndPoint, uriMap)

	// send get request
	code, body, err := restapi.HTTPGet(url)
	errResp, retErr := errorResponse(code, body, err)
	if retErr != nil {
		return errResp, retErr
	}

	var jobStatusList []openapi.JobStatus
	err = util.ByteToStruct(body, &jobStatusList)

	return openapi.Response(http.StatusOK, jobStatusList), err
}

// GetTask - Get a job task for a given job and task
func (s *JobsApiService) GetTask(ctx context.Context, jobId string, taskId string, key string) (openapi.ImplResponse, error) {
	if key == "" {
		return openapi.Response(http.StatusBadRequest, nil), fmt.Errorf("key can't be empty")
	}

	uriMap := map[string]string{
		constants.ParamJobID:  jobId,
		constants.ParamTaskID: taskId,
		constants.ParamKey:    key,
	}
	url := restapi.CreateURL(HostEndpoint, restapi.GetTaskEndpoint, uriMap)

	code, taskMap, err := restapi.HTTPGetMultipart(url)
	if err != nil {
		return openapi.Response(http.StatusInternalServerError, nil), fmt.Errorf("failed to fetch task")
	}

	if err = restapi.CheckStatusCode(code); err != nil {
		return openapi.Response(code, nil), err
	}

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

// GetTaskInfo - Get the info of a task in a job
func (s *JobsApiService) GetTaskInfo(ctx context.Context, user string, jobId string, taskId string) (openapi.ImplResponse, error) {
	uriMap := map[string]string{
		constants.ParamUser:   user,
		constants.ParamJobID:  jobId,
		constants.ParamTaskID: taskId,
	}
	url := restapi.CreateURL(HostEndpoint, restapi.GetTaskInfoEndpoint, uriMap)

	code, body, err := restapi.HTTPGet(url)
	errResp, retErr := errorResponse(code, body, err)
	if retErr != nil {
		return errResp, retErr
	}

	taskInfo := openapi.TaskInfo{}
	err = util.ByteToStruct(body, &taskInfo)

	return openapi.Response(http.StatusOK, taskInfo), err
}

// GetTasksInfo - Get the info of tasks in a job
func (s *JobsApiService) GetTasksInfo(ctx context.Context, user string, jobId string, limit int32) (openapi.ImplResponse, error) {
	uriMap := map[string]string{
		constants.ParamUser:    user,
		constants.ParamJobID:   jobId,
		constants.ParamLimit:   strconv.Itoa(int(limit)),
		constants.ParamGeneric: "false",
	}
	url := restapi.CreateURL(HostEndpoint, restapi.GetTasksInfoEndpoint, uriMap)

	code, body, err := restapi.HTTPGet(url)
	errResp, retErr := errorResponse(code, body, err)
	if retErr != nil {
		return errResp, retErr
	}

	var taskInfoList []openapi.TaskInfo
	err = util.ByteToStruct(body, &taskInfoList)

	return openapi.Response(http.StatusOK, taskInfoList), err
}

// GetTasksInfoGeneric - Get the info of tasks in a job
func (s *JobsApiService) GetTasksInfoGeneric(ctx context.Context, user string, jobId string, limit int32) (openapi.ImplResponse, error) {
	uriMap := map[string]string{
		constants.ParamUser:    user,
		constants.ParamJobID:   jobId,
		constants.ParamLimit:   strconv.Itoa(int(limit)),
		constants.ParamGeneric: "false",
	}
	url := restapi.CreateURL(HostEndpoint, restapi.GetTasksInfoEndpoint, uriMap)

	code, body, err := restapi.HTTPGet(url)
	errResp, retErr := errorResponse(code, body, err)
	if retErr != nil {
		return errResp, retErr
	}

	taskInfoList := []openapi.TaskInfo{}
	err = util.ByteToStruct(body, &taskInfoList)

	return openapi.Response(http.StatusOK, taskInfoList), err
}

// UpdateJob - Update a job specification
func (s *JobsApiService) UpdateJob(ctx context.Context, user string, jobId string,
	jobSpec openapi.JobSpec) (openapi.ImplResponse, error) {
	zap.S().Debugf("Job update request received for user: %s | jobId: %s", user, jobId)

	// create controller request
	uriMap := map[string]string{
		constants.ParamUser:  user,
		constants.ParamJobID: jobId,
	}
	url := restapi.CreateURL(HostEndpoint, restapi.UpdateJobEndPoint, uriMap)

	// send put request
	code, body, err := restapi.HTTPPut(url, jobSpec, "application/json")
	errResp, retErr := errorResponse(code, body, err)
	if retErr != nil {
		return errResp, retErr
	}

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

// UpdateJobStatus - Update the status of a job
func (s *JobsApiService) UpdateJobStatus(ctx context.Context, user string, jobId string,
	jobStatus openapi.JobStatus) (openapi.ImplResponse, error) {
	zap.S().Debugf("Job status update request received for user: %s | jobStatus: %v", user, jobStatus)

	// create controller request
	uriMap := map[string]string{
		constants.ParamUser:  user,
		constants.ParamJobID: jobId,
	}
	url := restapi.CreateURL(HostEndpoint, restapi.UpdateJobStatusEndPoint, uriMap)

	// send put request
	code, body, err := restapi.HTTPPut(url, jobStatus, "application/json")
	errResp, retErr := errorResponse(code, body, err)
	if retErr != nil {
		return errResp, retErr
	}

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

// UpdateTaskStatus - Update the status of a task
func (s *JobsApiService) UpdateTaskStatus(ctx context.Context, jobId string, taskId string,
	taskStatus openapi.TaskStatus) (openapi.ImplResponse, error) {
	zap.S().Debugf("Task status update request received for job %s | task: %s", jobId, taskId)

	// create controller request
	uriMap := map[string]string{
		constants.ParamJobID:  jobId,
		constants.ParamTaskID: taskId,
	}
	url := restapi.CreateURL(HostEndpoint, restapi.UpdateTaskStatusEndPoint, uriMap)

	// send put request
	code, body, err := restapi.HTTPPut(url, taskStatus, "application/json")
	errResp, retErr := errorResponse(code, body, err)
	if retErr != nil {
		return errResp, retErr
	}

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