package main

import (
	"errors"
	"fmt"
	"io"
	"log"
	"strings"

	"git.sr.ht/~xenrox/hut/srht/hubsrht"
	"git.sr.ht/~xenrox/hut/termfmt"
	"github.com/spf13/cobra"
)

func newHubCommand() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "hub",
		Short: "Use the hub API",
	}
	cmd.AddCommand(newHubListCommand())
	cmd.AddCommand(newHubShowCommand())
	return cmd
}

func newHubListCommand() *cobra.Command {
	var count, printed int
	run := func(cmd *cobra.Command, args []string) {
		ctx := cmd.Context()
		var cursor *hubsrht.Cursor
		var owner, instance string
		if len(args) > 0 {
			owner, instance = parseOwnerName(args[0])
		}

		err := pagerify(func(p pager) error {
			var projects *hubsrht.ProjectCursor
			if len(owner) > 0 {
				c := createClientWithInstance("hub", cmd, instance)
				username := strings.TrimLeft(owner, ownerPrefixes)
				user, err := hubsrht.ProjectsByUser(c.Client, ctx, username, cursor)
				if err != nil {
					return err
				} else if user == nil {
					return errors.New("no such user")
				}
				projects = user.Projects
			} else {
				c := createClient("hub", cmd)
				user, err := hubsrht.Projects(c.Client, ctx, cursor)
				if err != nil {
					return err
				}
				projects = user.Projects
			}

			for _, project := range projects.Results {
				if count != 0 && printed == count {
					return pagerDone
				}
				printProject(p, &project)
				printed += 1
			}

			cursor = projects.Cursor
			if p.IsDone(cursor, len(projects.Results)) {
				return pagerDone
			}
			return nil
		}, count)
		if err != nil {
			log.Fatal(err)
		}
	}

	cmd := &cobra.Command{
		Use:               "list [user]",
		Short:             "List projects",
		Args:              cobra.MaximumNArgs(1),
		ValidArgsFunction: cobra.NoFileCompletions,
		Run:               run,
	}
	cmd.Flags().IntVar(&count, "count", 0, "number of projects to fetch")
	cmd.RegisterFlagCompletionFunc("count", cobra.NoFileCompletions)
	return cmd
}

func newHubShowCommand() *cobra.Command {
	run := func(cmd *cobra.Command, args []string) {
		ctx := cmd.Context()
		name, owner, instance := parseResourceName(args[0])
		c := createClientWithInstance("hub", cmd, instance)

		var (
			user     *hubsrht.User
			username string
			err      error
		)
		if owner == "" {
			user, err = hubsrht.ProjectByName(c.Client, ctx, name)
		} else {
			username = strings.TrimLeft(owner, ownerPrefixes)
			user, err = hubsrht.ProjectByUser(c.Client, ctx, username, name)
		}
		if err != nil {
			log.Fatal(err)
		} else if user == nil {
			log.Fatalf("no such user %q", username)
		} else if user.Project == nil {
			log.Fatalf("no such project %q", name)
		}
		proj := user.Project

		if owner == "" {
			owner = proj.Owner.CanonicalName
		}

		showProject(proj, owner, c.Instance)
	}

	cmd := &cobra.Command{
		Use:               "show [project]",
		Short:             "Shows a project",
		Args:              cobra.ExactArgs(1),
		ValidArgsFunction: cobra.NoFileCompletions,
		Run:               run,
	}

	return cmd
}

func printProject(w io.Writer, p *hubsrht.Project) {
	fmt.Fprintf(w, "%s (%s)\n", termfmt.Bold.String(p.Name), p.Visibility.TermString())
	if p.Description != nil && *p.Description != "" {
		fmt.Fprintln(w, *p.Description)
	}
	if len(p.Tags) > 0 {
		for i, tag := range p.Tags {
			p.Tags[i] = "#" + tag
		}

		tags := strings.Join(p.Tags, " ")
		fmt.Fprintln(w, tags)
	}
	fmt.Fprintln(w)
}

func showProject(p *hubsrht.Project, owner string, inst *InstanceConfig) {
	fmt.Printf("%s (%s)\n",
		termfmt.Bold.String(p.Name),
		p.Visibility.TermString())
	if p.Description != nil && *p.Description != "" {
		fmt.Println(indent(strings.TrimSpace(*p.Description), "  "))
	}
	if p.Website != nil && *p.Website != "" {
		fmt.Println(indent("Website: "+strings.TrimSpace(*p.Website), "  "))
	}
	if len(p.Tags) > 0 {
		fmt.Println()
		for i, tag := range p.Tags {
			p.Tags[i] = "#" + tag
		}

		tags := strings.Join(p.Tags, " ")
		fmt.Println(indent("Tags: "+tags, "  "))
	}
	fmt.Println()
	fmt.Println(indent("Mailing lists:", "  "))
	if p.MailingLists != nil {
		baseURL := fmt.Sprintf("%s/%s/", inst.Services["lists"].Origin, owner)
		for _, l := range p.MailingLists.Results {
			link := termfmt.Hyperlink(baseURL+l.Name, l.Name)
			printProjectResource(link, l.Visibility.TermString(), l.Description)
		}
		if p.MailingLists.Cursor != nil {
			fmt.Println(indent("[...]", "    "))
		}
	}
	fmt.Println()
	fmt.Println(indent("Repositories:", "  "))
	if p.Sources != nil {
		gitURL := fmt.Sprintf("%s/%s/", inst.Services["git"].Origin, owner)
		hgURL := fmt.Sprintf("%s/%s/", inst.Services["hg"].Origin, owner)
		for _, r := range p.Sources.Results {
			var link string
			if r.RepoType == hubsrht.RepoTypeGit {
				link = termfmt.Hyperlink(gitURL+r.Name, r.Name)
			} else {
				link = termfmt.Hyperlink(hgURL+r.Name, r.Name)
			}

			printProjectResource(link, r.Visibility.TermString(), r.Description)
		}
		if p.Sources.Cursor != nil {
			fmt.Println(indent("[...]", "    "))
		}
	}
	fmt.Println()
	fmt.Println(indent("Trackers:", "  "))
	if p.Trackers != nil {
		baseURL := fmt.Sprintf("%s/%s/", inst.Services["todo"].Origin, owner)
		for _, t := range p.Trackers.Results {
			link := termfmt.Hyperlink(baseURL+t.Name, t.Name)
			printProjectResource(link, t.Visibility.TermString(), t.Description)
		}
		if p.Trackers.Cursor != nil {
			fmt.Println(indent("[...]", "    "))
		}
	}
	fmt.Println()
}

func printProjectResource(name string, visibility string, description *string) {
	fmt.Printf(indent("%s (%s)", "    "),
		termfmt.Bold.String(name), visibility)
	if description != nil && *description != "" {
		fmt.Printf("\n%s", indent(*description, "        "))
	}
	fmt.Println()
}
