package interactive

import (
	"fmt"
	"github.com/manifoldco/promptui"
	"gitlab.com/pcanilho/go-jira"
	"gitlab.com/pcanilho/go-jira-cli/cmd/helpers"
	"gitlab.com/pcanilho/go-jira-cli/internal"
	"strings"
)

type issueList struct {
	promptui.Select
	next, previous Menu
	controller     internal.IssueController
}

var issueListTemplate = &promptui.SelectTemplates{
	Label:    "{{ . }}?",
	Active:   "→ {{ .Key | cyan }} ({{ .ID | red }}) {{ if .Fields.Assignee }} ({{ .Fields.Assignee.Name | yellow }}) {{ else }} ({{ `unassigned` | faint | magenta }}) {{ end }}",
	Inactive: "  {{ .Key | cyan }} ({{ .ID | red }}) {{ if .Fields.Assignee }} ({{ .Fields.Assignee.Name | yellow }}) {{ else }} ({{ `unassigned` | faint | magenta }}) {{ end }}",
	Selected: "→ {{ .Key | red | cyan }}",
	Details: `
----------- Details ------------
{{ "Project:" | faint }}	  {{ .Fields.Project.Key }} ({{ .Fields.Project.Name | faint }}) 
{{ "Status:" | faint }}	 {{ if (eq .Fields.Status.Name "Open") }} {{ .Fields.Status.Name | faint | green }} {{ else if eq .Fields.Status.Name "To Do"}} {{ .Fields.Status.Name | faint | blue }} {{ else }} {{ .Fields.Status.Name | faint | red }} {{ end }}
{{ "Reporter:" | faint }}	  {{ .Fields.Reporter.Name }}
{{ "Created:" | faint }}	  {{ .Fields.Created | timeFormat }}
{{ "ID:" | faint }}	  {{ .ID }}
{{ "Key:" | faint }}  	  {{ .Key }}
{{ "Summary:" | faint }}  	  "{{ .Fields.Summary }}"
{{ "Labels:" | faint }}  	  {{ if eq (len .Fields.Labels) 0 }}{{ "empty" | faint | yellow }} {{ else }}"{{ .Fields.Labels }}"{{ end }}
{{ "Custom Fields #:" | faint }}    {{ len .Fields.Unknowns }}`,
	FuncMap: helpers.GenerateTemplateFuncMap(promptui.FuncMap),
}

func NewIssueListMenu(issues []jira.Issue, previous Menu) Menu {
	return &issueList{
		previous: previous,
		Select: promptui.Select{
			HideSelected: true,
			Label:        "-------- Issues --------",
			Templates:    issueListTemplate,
			Items:        issues,
			Searcher: func(input string, index int) bool {
				jiraIssue := issues[index]
				id := strings.TrimSpace(strings.ToLower(jiraIssue.ID))
				key := strings.TrimSpace(strings.ToLower(jiraIssue.Key))
				input = strings.Replace(strings.ToLower(input), " ", "", -1)

				return strings.Contains(id, input) || strings.Contains(key, input)
			},
		},
	}
}

func (mi *issueList) AttachController(controller internal.Controller) {
	mi.controller = controller
}

func (mi *issueList) Render() (int, string, error) {
	if mi.controller == nil {
		return -1, "", fmt.Errorf("the menu [controller] cannot be nil")
	}
	return mi.Run()
}