/*
 * Copyright 2021 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"
	"fmt"

	"github.com/spf13/cobra"

	"github.com/pingcap/mimir/pkg/protos"
	"github.com/pingcap/mimir/pkg/tui"
)

func newCreateIngress() *cobra.Command {
	var mqType, mqName string

	cmd := &cobra.Command{
		Use:   `create-ingress`,
		Short: `create ingress of your job access mimir`,
		RunE: func(cmd *cobra.Command, args []string) error {
			ctx := context.Background()

			client, err := newClient()
			if err != nil {
				return err
			}

			data, err := client.CreateIngress(ctx, &protos.CreateIngressParam{
				Name: mqName,
				Type: mqType,
			})
			if err != nil {
				return fmt.Errorf("create ingress failed: %s", err)
			}
			fmt.Println(data.Endpoint)
			return nil
		},
	}
	cmd.Flags().StringVar(&mqType, "type", "", "which mq you wanna create. Now we only support kafka and sqs")
	cmd.Flags().StringVar(&mqName, "name", "", "the name of your job topic")
	return cmd
}

func newRmIngress() *cobra.Command {
	var mqType, mqName string

	cmd := &cobra.Command{
		Use:   `rm-ingress`,
		Short: `rm ingress of your job access mimir`,
		RunE: func(cmd *cobra.Command, args []string) error {
			ctx := context.Background()

			client, err := newClient()
			if err != nil {
				return err
			}

			data, err := client.RmIngress(ctx, &protos.RmIngressParam{
				IngressID: mqName,
				Type:      mqType,
			})
			if err != nil {
				return fmt.Errorf("rm ingress failed: %s", err)
			}
			fmt.Println(data.IngressID)
			return nil
		},
	}
	cmd.Flags().StringVar(&mqType, "type", "", "which mq you wanna create. Now we only support kafka and sqs")
	cmd.Flags().StringVar(&mqName, "name", "", "the name of your job topic")
	return cmd
}

func newListIngressCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   `list-ingress`,
		Short: `display ingress list`,
		RunE: func(cmd *cobra.Command, args []string) error {
			ctx := context.Background()

			client, err := newClient()
			if err != nil {
				return err
			}

			data, err := client.ListIngress(ctx)
			if err != nil {
				return fmt.Errorf("list ingress failed: %s", err)
			}

			var ingressTable [][]string
			ingressTable = append(ingressTable, []string{"Ingress ID", "Type", "Endpoint"})
			for _, ingress := range data.Items {
				ingressTable = append(ingressTable, []string{ingress.IngressID, ingress.Type, ingress.Endpoint})
			}
			tui.PrintTable(ingressTable, true)

			return nil
		},
	}

	return cmd
}
