package client

import (
	"context"
	"io"
	"net/url"
	"time"

	"github.com/alibaba/pouch/apis/types"
	"github.com/alibaba/pouch/pkg/utils"
)

// ContainerLogs return the logs generated by a container in an io.ReadCloser.
func (client *APIClient) ContainerLogs(ctx context.Context, name string, options types.ContainerLogsOptions) (io.ReadCloser, error) {
	now := time.Now()

	query := url.Values{}
	if options.ShowStdout {
		query.Set("stdout", "1")
	}

	if options.ShowStderr {
		query.Set("stderr", "1")
	}

	if options.Since != "" {
		sinceTs, err := utils.GetUnixTimestamp(options.Since, now)
		if err != nil {
			return nil, err
		}
		query.Set("since", sinceTs)
	}

	if options.Until != "" {
		untilTs, err := utils.GetUnixTimestamp(options.Until, now)
		if err != nil {
			return nil, err
		}
		query.Set("until", untilTs)
	}

	if options.Timestamps {
		query.Set("timestamps", "1")
	}

	if options.Follow {
		query.Set("follow", "1")
	}

	if options.Details {
		query.Set("details", "1")
	}
	query.Set("tail", options.Tail)

	resp, err := client.get(ctx, "/containers/"+name+"/logs", query, nil)
	if err != nil {
		return nil, err
	}
	return resp.Body, nil
}
