package cmd

import (
	"fmt"
	"github.com/pkg/errors"
	"gitlab.com/pcanilho/go-jira-cli/internal"
	"os"
	"strings"
)

/****************** Flags ******************/

var (
	description, project, issueType string            // Create, Clone & Search
	assignee, clone, priority       string            // Create
	labels, components              []string          // Create
	summary                         string            // Update & Create
	attachments                     []string          // Update
	commentBody                     string            // Create, Update -> Add -> Comment
	limitResults, maxOccurrences    int               // Search
	customFields                    map[string]string // Common
	expand                          bool              // Common
	status                          string            // Search
)

func isInPipe() bool {
	fileStat, _ := os.Stdin.Stat()
	return fileStat.Mode()&os.ModeCharDevice == 0
}

func attachmentFromPath(path string) (*internal.IssueAttachment, error) {
	raw := strings.Split(path, ":")
	if len(raw) > 1 {
		name, path = raw[0], raw[1]
	} else {
		name, path = raw[0], raw[0]
	}

	// File leak (sdk doesn't close the resource) ?!?!?
	fi, err := os.Stat(path)
	if err != nil {
		return nil, errors.Wrapf(err, "unable to state file at [%s]", path)
	}
	if fi.IsDir() {
		return nil, fmt.Errorf("the path [%s] is a directory, a file must be provided instead", path)
	}

	f, err := os.Open(path)
	if err != nil {
		return nil, errors.Wrapf(err, "unable to open the file at [%s]", path)
	}
	return &internal.IssueAttachment{
		Reader:   f,
		Filename: name,
	}, nil
}