package slowlog

import (
	"context"
	"github.com/pingcap/tep/pkg/apis/apiserver"
	store "github.com/pingcap/tep/pkg/registry/apiserver"
	"github.com/pingcap/tep/pkg/utils"
	metainternalversion "k8s.io/apimachinery/pkg/apis/meta/internalversion"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apiserver/pkg/endpoints/request"
)

type TiDBSlowLogStorage struct {
	store *store.Store
}

func NewStorage(store *store.Store) *TiDBSlowLogStorage {
	return &TiDBSlowLogStorage{
		store: store,
	}
}

func (s *TiDBSlowLogStorage) Kind() string {
	return "TiDBSlowLog"
}

func (s *TiDBSlowLogStorage) New() runtime.Object {
	return &apiserver.TiDBSlowLog{}
}

func (s *TiDBSlowLogStorage) NewList() runtime.Object {
	return &apiserver.TiDBSlowLogList{}
}

func (s *TiDBSlowLogStorage) NamespaceScoped() bool {
	return true
}

func (s *TiDBSlowLogStorage) NewExtraListOptions() runtime.Object {
	return &apiserver.TiDBSlowLogListOptions{}
}

func (s *TiDBSlowLogStorage) List(ctx context.Context, options *metainternalversion.ListOptions, extraOptions runtime.Object) (runtime.Object, error) {
	listOptions := extraOptions.(*apiserver.TiDBSlowLogListOptions)
	namespace := request.NamespaceValue(ctx)
	return s.ListSlowLog(Context{
		From:           utils.GetStartIndex(listOptions.Page, listOptions.ItemsPerPage),
		Size:           utils.GetSize(listOptions.ItemsPerPage),
		StartTimeInSec: listOptions.StartTimeInSec,
		EndTimeInSec:   listOptions.EndTimeInSec,
		Namespace:      namespace,
	})
}
