package repostatus

import (
	"os"
	"path/filepath"
	"strings"

	"go.wit.com/gui"
	"go.wit.com/lib/gadgets"
	"go.wit.com/log"
)

var windowMap map[string]*RepoStatus

func ListAll() {
	for path, rs := range windowMap {
		log.Warn(rs.GetMasterVersion(), path)
	}
}

func NewRepoStatusWindow(path string) *RepoStatus {
	if windowMap[path] == nil {
		log.Log(INFO, "NewRepoStatusWindow() adding new", path)
	} else {
		log.Warn("This already exists yet for path", path)
		log.Warn("should return windowMap[path] here")
		return windowMap[path]
	}

	homeDir, err := os.UserHomeDir()
	if err != nil {
		log.Log(WARN, "Error getting home directory:", err)
		return nil
	}

	goSrcDir := filepath.Join(homeDir, "go/src")
	realpath := filepath.Join(goSrcDir, path)

	filename := filepath.Join(goSrcDir, path, ".git/config")

	_, err = os.Open(filename)
	if err != nil {
		log.Log(WARN, "Error reading .git/config:", filename, err)
		log.Log(WARN, "TODO: find .git/config in parent directory")
		// return nil
	}

	rs := New(gui.TreeRoot(), path)
	rs.draw()

	// save ~/go/src & the whole path strings
	rs.path.SetValue(path)
	rs.goSrcPath.SetValue(goSrcDir)
	rs.realPath.SetValue(realpath)

	rs.readGitConfig()

	rs.readOnly.SetValue("true")
	if strings.HasPrefix(path, "go.wit.com") {
		rs.readOnly.SetValue("false")
	}
	if strings.HasPrefix(path, "git.wit.org") {
		rs.readOnly.SetValue("false")
	}

	windowMap[path] = rs

	// todo check if a window already exists for this path
	return rs
}

func New(p *gui.Node, path string) *RepoStatus {
	rs := &RepoStatus{
		hidden: true,
		ready:  false,
		parent: p,
	}
	rs.tags = make(map[string]string)
	rs.window = gadgets.NewBasicWindow(p, "GO Repo Details "+path)
	rs.window.Horizontal()
	rs.window.Make()
	rs.ready = true
	rs.window.Custom = func() {
		// rs.hidden = true
		rs.Hide()
		log.Warn("repostatus user closed the window()")
	}
	windowMap[path] = rs
	return rs
}

func init() {
	windowMap = make(map[string]*RepoStatus)
}