package models

import (
	"strings"
)

type ArgoWatch struct {
	Name      string
	Namespace string
	Status    string
	Conditions
	Created  string
	Started  string
	Duration string
	Progress string
}

type Conditions struct {
	PodRunning bool
	Completed  bool
}

func (a *ArgoWatch) Equals(arg ArgoWatch) bool {
	return a.Status == arg.Status && a.Progress == arg.Progress && a.Conditions.PodRunning == arg.Conditions.PodRunning && a.Conditions.Completed == arg.Conditions.Completed
}

// Take the slice of string that make up one round of stderr outputs from the --watch option in argo submit
func NewArgoLogs(inputs []string) *ArgoWatch {
	var workflow ArgoWatch

	for _, input := range inputs {
		line := strings.TrimSpace(input)
		if line == "" {
			continue
		}
		switch {
		case strings.HasPrefix(line, "Name:"):
			workflow.Name = parseValue(line)
		case strings.HasPrefix(line, "Namespace:"):
			workflow.Namespace = parseValue(line)
		case strings.HasPrefix(line, "Status:"):
			workflow.Status = parseValue(line)
		case strings.HasPrefix(line, "PodRunning"):
			workflow.PodRunning = parseBoolValue(line)
		case strings.HasPrefix(line, "Completed"):
			workflow.Completed = parseBoolValue(line)
		case strings.HasPrefix(line, "Created:"):
			workflow.Created = parseValue(line)
		case strings.HasPrefix(line, "Started:"):
			workflow.Started = parseValue(line)
		case strings.HasPrefix(line, "Duration:"):
			workflow.Duration = parseValue(line)
		case strings.HasPrefix(line, "Progress:"):
			workflow.Progress = parseValue(line)
		}
	}

	return &workflow
}

func parseValue(line string) string {
	parts := strings.SplitN(line, ":", 2)
	if len(parts) < 2 {
		return ""
	}
	return strings.TrimSpace(parts[1])
}

func parseBoolValue(line string) bool {
	value := parseValue(line)
	return value == "True"
}
