/*
Copyright 2020 The Skaffold Authors

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,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package util

import (
	"fmt"
	"io"

	"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/logfile"
	"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/output"
)

// TimeFormat is used to name log files generated by deploy step
const TimeFormat = "2006-01-02_15-04-05"

type Muted interface {
	MuteStatusCheck() bool
	MuteDeploy() bool
}

// WithLogFile returns a file to write the deploy output to, and a function to be executed after the deploy step is complete.
func WithLogFile(filename string, out io.Writer, muted Muted) (io.Writer, func(), error) {
	if !muted.MuteDeploy() {
		return out, func() {}, nil
	}

	file, err := logfile.Create("deploy", filename)
	if err != nil {
		return out, func() {}, fmt.Errorf("unable to create log file for deploy step: %w", err)
	}

	output.Default.Fprintln(out, "Starting deploy...")
	fmt.Fprintln(out, "- writing logs to", file.Name())

	// After the deploy finishes, close the log file.
	return file, func() {
		file.Close()
	}, err
}

// WithStatusCheckLogFile returns a file to write the status-check output to, and a function to be executed after the status-check step is complete.
func WithStatusCheckLogFile(filename string, out io.Writer, muted Muted) (io.Writer, func(), error) {
	if !muted.MuteStatusCheck() {
		return out, func() {}, nil
	}

	file, err := logfile.Create("status-check", filename)
	if err != nil {
		return out, func() {}, fmt.Errorf("unable to create log file for deploy step: %w", err)
	}

	output.Default.Fprintln(out, "Waiting for deployments to stabilize...")
	fmt.Fprintln(out, "- writing logs to", file.Name())

	// After the status-check finishes, close the log file.
	return file, func() {
		file.Close()
	}, err
}
