/*
 * 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"
	"io"
	"os"
	"time"

	"github.com/spf13/cobra"

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

func newLogsCmd() *cobra.Command {
	follow := false
	timestamps := false
	previous := false
	sinceSeconds := int64(0)
	limitBytes := int64(0)
	tailLines := int64(-1)
	sinceTime := ""

	cmd := &cobra.Command{
		Use:   `logs <job-id>`,
		Short: `Print the logs for a specified job`,
		RunE: func(cmd *cobra.Command, args []string) error {
			if len(args) != 1 {
				return cmd.Help()
			}

			opts := &protos.GetLogsParam{
				JobID:      args[0],
				Follow:     follow,
				Timestamps: timestamps,
				Previous:   previous,
			}
			if limitBytes > 0 {
				opts.LimitBytes = &limitBytes
			}
			if sinceSeconds > 0 {
				opts.SinceSeconds = &sinceSeconds
			}
			if tailLines >= 0 {
				opts.TailLines = &tailLines
			}
			if sinceTime != "" {
				t, err := time.Parse(time.RFC3339, sinceTime)
				if err != nil {
					return fmt.Errorf("can't parse time: %s", err)
				}
				opts.SinceSeconds = nil
				opts.SinceTime = &t
			}

			ctx := context.Background()

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

			stream, err := client.GetLogs(ctx, opts)
			if err != nil {
				return fmt.Errorf("get job log failed: %s", err)
			}
			defer stream.Close()

			_, err = io.Copy(os.Stdout, stream)
			return err
		},
	}

	cmd.Flags().BoolVarP(&follow, "follow", "f", follow, "Specify if the logs should be streamed")
	cmd.Flags().BoolVarP(&timestamps, "timestamps", "", timestamps, "Include timestamps on each line in the log output")
	cmd.Flags().BoolVarP(&previous, "previous", "p", previous, "If true, print the logs for the previous instance of the container in a pod if it exists")
	cmd.Flags().Int64VarP(&sinceSeconds, "since", "", sinceSeconds, "Only return logs newer than a relative duration in seconds")
	cmd.Flags().Int64VarP(&limitBytes, "limit-bytes", "", limitBytes, "Maximum bytes of logs to return. Defaults to no limit")
	cmd.Flags().Int64VarP(&tailLines, "tail", "", tailLines, "Lines of recent log file to display. Defaults to -1, showing all log lines")
	cmd.Flags().StringVarP(&sinceTime, "since-time", "", sinceTime, "Only return logs after a specific date (RFC3339). Defaults to all logs. Only one of since-time / since may be used")

	return cmd
}
