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

	"github.com/pingcap/tidb-cloud-manager/managerctl/cmd/util"
	"github.com/spf13/cobra"
)

//PasswdOptions contains the options related to reset password command
type PasswdOptions struct {
	Namespace string
	Password  string
}

//NewCmdResetPasswd creates the command for reset Tidb's password
func NewCmdResetPasswd(cli util.Client) *cobra.Command {
	var options PasswdOptions

	cmd := &cobra.Command{
		Use:   "reset -p PASSWORD -n NAMESPACE",
		Short: "Reset tidb cluster's password.",
		Long:  "Reset tidb cluster's password.",
		Run: func(cmd *cobra.Command, args []string) {
			util.ValidCmdFlags(cmd)
			util.CheckErr(util.ValidManagerAddr(cmdFlags.URL))
			util.CheckErr(RunResetPaswd(cli, &options))
		},
	}

	cmd.Flags().StringVarP(&options.Namespace, "namespace", "n", "", "Namespace for tidb cluster.")
	cmd.Flags().StringVarP(&options.Password, "password", "p", "", "Password for tidb cluster.")
	return cmd
}

func RunResetPaswd(cli util.Client, options *PasswdOptions) error {
	suffix := fmt.Sprintf("%s/password", options.Namespace)
	fullURL := util.GetClusterURL(cmdFlags.URL, suffix)
	passwordBytes, _ := json.Marshal(
		map[string]string{
			"root_password": options.Password,
		},
	)
	resp, err := cli.DoPut(fullURL, util.ContentType, passwordBytes)
	if err != nil {
		return err
	}
	return util.OutputResp(resp)
}
