package mytelegram

import "testing"

// TestFindInputValue mirrors the hidden <input name="hash"> present on
// my.telegram.org/apps before creating an application.
func TestFindInputValue(t *testing.T) {
	html := []byte(`<div><form action="/apps/create" method="post">
		<input type="hidden" name="hash" value="abc123def456">
		<input type="text" name="app_title">
	</form></div>`)
	got, ok := findInputValue(html, "hash")
	if !ok {
		t.Fatal("expected to find hash input")
	}
	if got != "abc123def456" {
		t.Fatalf("got %q, want abc123def456", got)
	}
}

// TestFindInputValueAttributeOrder ensures the parser handles value-before-name
// and other attribute orderings, which real HTML does.
func TestFindInputValueAttributeOrder(t *testing.T) {
	html := []byte(`<input value="zzz999" type="hidden" name="hash" id="h">`)
	got, ok := findInputValue(html, "hash")
	if !ok {
		t.Fatal("expected to find hash input")
	}
	if got != "zzz999" {
		t.Fatalf("got %q, want zzz999", got)
	}
}

// TestFindUneditableInputs mirrors the two <span> elements that hold api_id
// and api_hash after a successful app creation on /apps.
func TestFindUneditableInputs(t *testing.T) {
	html := []byte(`<div class="form-group">
		<label>App api_id:</label>
		<span class="form-control input-xlarge uneditable-input" id="app-id">1234567</span>
		<label>App api_hash:</label>
		<span class="form-control input-xlarge uneditable-input" id="app-hash">0123456789abcdef0123456789abcdef</span>
	</div>`)
	creds := findUneditableInputs(html)
	if len(creds) < 2 {
		t.Fatalf("expected at least 2 spans, got %d", len(creds))
	}
	if creds[0] != "1234567" {
		t.Fatalf("api_id: got %q, want 1234567", creds[0])
	}
	if creds[1] != "0123456789abcdef0123456789abcdef" {
		t.Fatalf("api_hash: got %q", creds[1])
	}
}

// TestProxyURL covers the proxy rendering for each kind.
func TestProxyURL(t *testing.T) {
	cases := []struct {
		p    Proxy
		want string
	}{
		{Proxy{Kind: "none"}, ""},
		{Proxy{Kind: "http", Host: "1.2.3.4", Port: 8080}, "http://1.2.3.4:8080"},
		{Proxy{Kind: "socks5", Host: "h", Port: 1080, Username: "u", Password: "p"}, "socks5://u:p@h:1080"},
	}
	for _, c := range cases {
		got := c.p.URL()
		if got != c.want {
			t.Errorf("Proxy{Kind:%s Host:%s Port:%d}.URL() = %q, want %q", c.p.Kind, c.p.Host, c.p.Port, got, c.want)
		}
	}
}
