//go:build go1.16
// +build go1.16

/*
 * Copyright (c) 2021 Gilles Chehade <gilles@poolp.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

package ui

import (
	"flag"
	"fmt"

	"github.com/PlakarKorp/kloset/repository"
	"github.com/PlakarKorp/plakar/appcontext"
	"github.com/PlakarKorp/plakar/subcommands"
	v2 "github.com/PlakarKorp/plakar/ui/v2"
	"github.com/google/uuid"
)

func init() {
	subcommands.Register(func() subcommands.Subcommand { return &Ui{} }, subcommands.AgentSupport, "ui")
}

func (cmd *Ui) Parse(ctx *appcontext.AppContext, args []string) error {
	flags := flag.NewFlagSet("ui", flag.ExitOnError)
	flags.Usage = func() {
		fmt.Fprintf(flags.Output(), "Usage: %s [OPTIONS]\n", flags.Name())
		fmt.Fprintf(flags.Output(), "\nOPTIONS:\n")
		flags.PrintDefaults()
	}

	flags.StringVar(&cmd.Addr, "addr", "", "address to listen on (default: random port on localhost)")
	flags.BoolVar(&cmd.Cors, "cors", false, "enable CORS")
	flags.BoolVar(&cmd.NoAuth, "no-auth", false, "don't use authentication")
	flags.BoolVar(&cmd.NoSpawn, "no-spawn", false, "don't spawn browser")
	flags.Parse(args)

	if flags.NArg() > 0 {
		return fmt.Errorf("Too many arguments")
	}

	cmd.RepositorySecret = ctx.GetSecret()

	return nil
}

type Ui struct {
	subcommands.SubcommandBase

	Addr    string
	Cors    bool
	NoAuth  bool
	NoSpawn bool
}

func (cmd *Ui) Execute(ctx *appcontext.AppContext, repo *repository.Repository) (int, error) {
	ui_opts := v2.UiOptions{
		NoSpawn: cmd.NoSpawn,
		Cors:    cmd.Cors,
		Token:   "",
	}

	if !cmd.NoAuth {
		ui_opts.Token = uuid.NewString()
	}

	err := v2.Ui(repo, ctx, cmd.Addr, &ui_opts)
	if err != nil {
		fmt.Fprintf(ctx.Stderr, "ui: %s\n", err)
		return 1, err
	}
	return 0, err
}
