// Copyright 2022 PingCAP, Inc.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
	"context"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/gorilla/mux"
	"github.com/pingcap/fn"
	"github.com/pingcap/log"
	"go.uber.org/zap"

	"github.com/pingcap-inc/compute-engine/pkg/database/model"
	"github.com/pingcap-inc/compute-engine/pkg/service"
)

type SearchRequest struct {
	Tags map[string]interface{} `json:"tags"`
	Args map[string]interface{} `json:"args"`
	Data map[string]interface{} `json:"data"`
}

type SearchResponse []model.TaskInstance

func SearchInstance(ctx context.Context, req *http.Request, params *SearchRequest) (SearchResponse, error) {
	task := mux.Vars(req)["task"]

	query := req.URL.Query()
	statusStr := query.Get("status")
	beginStr := query.Get("begin")
	endStr := query.Get("end")

	var status model.TaskStatus
	if statusStr == "" {
		status = model.Pending | model.Running | model.Failed | model.Success
	} else {
		for _, s := range []model.TaskStatus{model.Pending, model.Running, model.Failed, model.Success} {
			for _, ss := range strings.Split(statusStr, ",") {
				if s.String() == ss {
					status |= s
				}
			}
		}
	}

	var begin *time.Time
	if beginStr != "" {
		i, err := strconv.ParseInt(beginStr, 10, 64)
		if err != nil {
			log.Info("parse begin time error", zap.Error(err))
			return nil, fn.ErrorWithStatusCode(err, http.StatusBadRequest)
		}
		t := time.Unix(i, 0)
		begin = &t
	}

	var end *time.Time
	if endStr != "" {
		i, err := strconv.ParseInt(endStr, 10, 64)
		if err != nil {
			log.Info("parse end time error", zap.Error(err))
			return nil, fn.ErrorWithStatusCode(err, http.StatusBadRequest)
		}
		t := time.Unix(i, 0)
		end = &t
	}

	// Limit the result to an hour if no time limit specified
	if begin == nil && end == nil {
		t := time.Now().Add(time.Duration(-1) * time.Hour)
		begin = &t
	}

	s := ctx.Value(InstanceKey).(service.Scheduler)
	ids, err := s.SearchInstance(ctx, task, status, begin, end, params.Tags, params.Args, params.Data)
	if err != nil {
		log.Error("search instance ids error", zap.Error(err))
		return nil, fn.ErrorWithStatusCode(err, http.StatusInternalServerError)
	}
	insts, err := s.ListInstance(ctx, ids)
	if err != nil {
		log.Error("list instance error", zap.Error(err))
		return nil, fn.ErrorWithStatusCode(err, http.StatusInternalServerError)
	}
	return insts, nil
}

// SearchInstanceLight is SearchInstance without tags and data query
func SearchInstanceLight(ctx context.Context, req *http.Request) (SearchResponse, error) {
	return SearchInstance(ctx, req, &SearchRequest{})
}
