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

import (
	"encoding/json"
	"fmt"
	"strings"

	"github.com/pingcap/tidb-cloud-manager/managerctl/cmd/util"
	"github.com/spf13/cobra"
	"k8s.io/apimachinery/pkg/labels"
)

//NewCmdCreateBackup implements the create subcommand of backup
func NewCmdCreateBackup(cli util.Client) *cobra.Command {
	var options BackupOptions

	cmd := &cobra.Command{
		Use:   "create -n NAMESPACE -B DATABASE -T TABLES -F CHUNKS -t THREADS -i IMAGE_VERSION",
		Short: "Create a backup task for specific tidb cluster.",
		Long:  "Create a backup task for specific tidb cluster.",
		Run: func(cmd *cobra.Command, args []string) {
			util.ValidCmdFlags(cmd)
			util.CheckErr(util.ValidManagerAddr(cmdFlags.URL))
			util.CheckErr(RunCreateBackup(cli, &options))
		},
	}

	cmd.Flags().StringVarP(&options.Namespace, "namespace", "n", "", "Namespace of tidb cluster.")
	cmd.Flags().StringVarP(&options.Database, "database", "B", "", "Database to dump")
	cmd.Flags().StringVarP(&options.Tables, "tables", "T", "all", "Comma delimited table list to dump, default all represent dump the entire database")
	cmd.Flags().StringVarP(&options.NodeSelector, "node_selector", "s", "", "Select a specific node to backup, e.g. -s kubernetes.io/hostname=kube-node-2,kind=tidb")
	cmd.Flags().StringVarP(&options.ImageVersion, "image_version", "i", "latest", "The tidb-enterprise-tools docker image version")
	cmd.Flags().IntVarP(&options.Chunks, "chunks", "F", 64, "Split tables into chunks of this output file size. This value is in MB, default 64")
	cmd.Flags().IntVarP(&options.Threads, "threads", "t", 16, "Number of threads to use, default 16")

	return cmd
}

func RunCreateBackup(cli util.Client, options *BackupOptions) error {
	tables := strings.Split(options.Tables, ",")
	if options.Tables != "all" && len(tables) != 0 {
		options.BackupParam.Tables = tables
	}

	nodeSelector, err := labels.ConvertSelectorToLabelsMap(options.NodeSelector)
	if err != nil {
		return fmt.Errorf("invalid node selector format, err: %s", err.Error())
	}
	options.BackupParam.NodeSelector = nodeSelector
	suffix := fmt.Sprintf("%s/backup", options.Namespace)
	fullURL := util.GetClusterURL(cmdFlags.URL, suffix)
	bkBytes, err := json.Marshal(options.BackupParam)
	if err != nil {
		return err
	}
	resp, err := cli.DoPost(fullURL, util.ContentType, bkBytes)
	if err != nil {
		return err
	}
	return util.OutputResp(resp)
}
