// Copyright 2017 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 spec

package client

import (
	"github.com/juju/errors"
	"github.com/pingcap/tidb-cloud-manager/pkg/api"
	tiapi "github.com/pingcap/tidb-cloud-manager/pkg/tidbinstance/api"
	opclient "github.com/pingcap/private-tidb-operator/pkg/client"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/serializer"
	"k8s.io/apimachinery/pkg/watch"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
)

// Interface is a mixin of kubernetes.Interface with TiDBInstance client interface
type Interface interface {
	kubernetes.Interface
	PingcapV1() PingcapV1Interface
}

// PingcapV1Interface is a mixin of TiDBInstance client interface with TiDBCluster and TiDBSet interface
type PingcapV1Interface interface {
	TidbInstances(string) TidbInstancesInterface
	opclient.PingcapV1Interface
}

// TidbInstancesInterface is TiDBInstance interface
type TidbInstancesInterface interface {
	Create(*tiapi.TidbInstance) (*tiapi.TidbInstance, error)
	List(metav1.ListOptions) (*tiapi.TidbInstanceList, error)
	Get(string, metav1.GetOptions) (*tiapi.TidbInstance, error)
	Delete(string, *metav1.DeleteOptions) error
	Update(*tiapi.TidbInstance) (*tiapi.TidbInstance, error)
	Watch(metav1.ListOptions) (watch.Interface, error)
}

// New Creates an Interface
func New(kubeconfig string) (Interface, error) {
	cfg, err := opclient.NewConfig(kubeconfig)
	if err != nil {
		return nil, errors.Trace(err)
	}
	kubeCli, err := kubernetes.NewForConfig(cfg)
	if err != nil {
		return nil, errors.Trace(err)
	}

	scheme := runtime.NewScheme()
	if err := api.AddToScheme(scheme); err != nil {
		return nil, errors.Trace(err)
	}

	cfg.GroupVersion = &api.SchemeGroupVersion
	cfg.APIPath = "/apis"
	cfg.ContentType = runtime.ContentTypeJSON
	cfg.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: serializer.NewCodecFactory(scheme)}

	cli, err := rest.RESTClientFor(cfg)
	if err != nil {
		return nil, errors.Trace(err)
	}
	return &client{
		Clientset:       kubeCli,
		PingcapV1Client: &opclient.PingcapV1Client{cli},
		pingcapV1Client: &pingcapV1Client{cli, &opclient.PingcapV1Client{cli}},
	}, nil
}

type client struct {
	*kubernetes.Clientset
	*opclient.PingcapV1Client
	*pingcapV1Client
}

func (c *client) PingcapV1() PingcapV1Interface {
	if c == nil {
		return nil
	}
	return c.pingcapV1Client
}

type pingcapV1Client struct {
	*rest.RESTClient
	*opclient.PingcapV1Client
}

func (c *pingcapV1Client) TidbInstances(ns string) TidbInstancesInterface {
	return newTidbInstances(c, ns)
}

type tidbInstances struct {
	client *pingcapV1Client
	ns     string
}

func newTidbInstances(cli *pingcapV1Client, ns string) *tidbInstances {
	return &tidbInstances{cli, ns}
}

// Create creates a new TidbInstance
func (tis *tidbInstances) Create(tidbinstance *tiapi.TidbInstance) (*tiapi.TidbInstance, error) {
	result := &tiapi.TidbInstance{}
	err := tis.client.Post().
		Namespace(tis.ns).
		Resource(tiapi.TidbInstanceResourcePlural).
		Body(tidbinstance).
		Do().
		Into(result)
	return result, err
}

// List takes a selector, and returns the list of TidbInstances that match that selector
func (tis *tidbInstances) List(opts metav1.ListOptions) (*tiapi.TidbInstanceList, error) {
	result := &tiapi.TidbInstanceList{}
	err := tis.client.Get().
		Namespace(tis.ns).
		Resource(tiapi.TidbInstanceResourcePlural).
		VersionedParams(&opts, metav1.ParameterCodec).
		Do().
		Into(result)
	return result, err
}

// Get returns a TidbInstance
func (tis *tidbInstances) Get(name string, opts metav1.GetOptions) (*tiapi.TidbInstance, error) {
	result := &tiapi.TidbInstance{}
	err := tis.client.Get().
		Namespace(tis.ns).
		Resource(tiapi.TidbInstanceResourcePlural).
		Name(name).
		VersionedParams(&opts, metav1.ParameterCodec).
		Do().
		Into(result)
	return result, err
}

// Delete takes the name of the endpoint, and returns an error if one occurs
func (tis *tidbInstances) Delete(name string, opts *metav1.DeleteOptions) error {
	return tis.client.Delete().
		Namespace(tis.ns).
		Resource(tiapi.TidbInstanceResourcePlural).
		Name(name).
		Body(opts).
		Do().
		Error()
}

// Watch returns a watch.Interface that watches the requested TidbInstances
func (tis *tidbInstances) Watch(opts metav1.ListOptions) (watch.Interface, error) {
	return tis.client.Get().
		Prefix("watch").
		Namespace(tis.ns).
		Resource(tiapi.TidbInstanceResourcePlural).
		VersionedParams(&opts, metav1.ParameterCodec).
		Watch()
}

// Update update a TidbInstance
func (tis *tidbInstances) Update(tidbinstance *tiapi.TidbInstance) (*tiapi.TidbInstance, error) {
	result := &tiapi.TidbInstance{}
	err := tis.client.Put().
		Namespace(tis.ns).
		Resource(tiapi.TidbInstanceResourcePlural).
		Name(tidbinstance.Name).
		Body(tidbinstance).
		Do().
		Into(result)
	return result, err
}
