package main

import "log"
import "os"
import "bufio"
import "strings"
import "errors"
import "git.wit.org/wit/gui"

var filename string = "resolv-1-1-1-1.conf"
var generaloutput *gui.Node

func resolvWindow(w *gui.Node) {
	if (w == nil) {
		gui.Config.Title = "resolv.conf Window"
		gui.Config.Width = 113
		gui.Config.Height = 112
		gui.Config.Exit = nil
		w = gui.NewWindow()
	}

	tab := w.AddTab("resolv.conf Tab", nil)
	// populateNEW(tab, "new")

//////////////   filename    /////////////////////////
	gNode := tab.AddGroup("filename")

	var tmp []string
	for i, s := range packrBox.List() {
		log.Println("i, s =", i, s)
		if strings.HasPrefix(s, "resolv/") {
			tmp = append(tmp, s)
		}
	}
	// panic("junk")

	resolvNode := gNode.AddComboBox("test", tmp...)

	resolvNode.SetText(filename)
	resolvNode.OnChanged = func () {
		log.Println("STARTED HOSTNAME")
		filename = resolvNode.GetText()
		log.Println("ENDED GetText() HOSTNAME =", filename)
	}

//////////////   connect     /////////////////////////
	gNode = tab.AddGroup("Update")

	gNode.AddButton("Update /etc/resolv.conf", func (*gui.Node) {
		sudo( func() error {
			log.Println("set resolv.conf to",filename)
			b, _ := packrBox.FindString(filename)
			log.Println(filename, "=\n\n" + b)
			// spew.Dump(b)

			f, err := os.Create("/etc/resolv.conf")
			if err != nil {
				return errors.New("os.Create() /etc/resolv.conf failed")
			}
			defer f.Close()
			w := bufio.NewWriter(f)
			n4, err := w.WriteString(b)
			log.Println("n4 =", n4)
			w.Flush()
			return nil
		})
	})
	gNode.AddButton("test ping ipv4", func (*gui.Node) {
		bash("ping -c 3 1.1.1.1")
	})
	gNode.AddButton("test ping ipv6", func (*gui.Node) {
		bash("ping -c 3 2001:4860:4860::6464")
	})

	gui.Config.Stretchy = true
	gNode.AddButton("set output", func (*gui.Node) {
		if (generaloutput != nil) {
			generaloutput.SetText("wow")
			generaloutput.SetMargined(false)
		}
	})
	gui.Config.Stretchy = false

	gui.Config.Stretchy = true
	gNode = tab.AddGroup("Update")
	generaloutput = gNode.MakeGroupEdit("output")
	gui.Config.Stretchy = false
}