package main

import (
	"os"
	"runtime"
	"strings"
	"testing"
)

func TestParseConfig(t *testing.T) {
	// Set permissions.
	testfiles := []string{
		"testdata/config001", "testdata/config002",
		"testdata/config003", "testdata/config004",
	}
	for i, file := range testfiles {
		switch i {
		case 1:
			err := os.Chmod(file, 0o444)
			if err != nil {
				t.Errorf("Failed to set permissions for %s", file)
			}
		default:
			err := os.Chmod(file, 0o400)
			if err != nil {
				t.Errorf("Failed to set permissions for %s", file)
			}
		}
	}
	// Test good config.
	cfg, err := parseConfig("testdata/config001")
	if err != nil {
		t.Fatalf("Failed to parse config: %v", err)
	}
	if cfg.username != "user@example.com" {
		t.Errorf("Expected username 'user@example.com', got '%s'", cfg.username)
	}
	if cfg.password != "hunter2" {
		t.Errorf("Expected password 'hunter2', got '%s'", cfg.password)
	}
	if cfg.jserver != "xmpp.example.com" {
		t.Errorf("Expected jserver 'xmpp.example.com', got '%s'", cfg.jserver)
	}
	if cfg.port != "1234" {
		t.Errorf("Expected port '1234', got '%s'", cfg.port)
	}
	if cfg.alias != "bla" {
		t.Errorf("Expected alias 'bla', got '%s'", cfg.alias)
	}

	if runtime.GOOS != "windows" {
		// Bad permissions.
		cfg, err = parseConfig("testdata/config002")
		if err == nil {
			t.Fatalf("Expected an error, got nil")
		}
		if !strings.Contains(err.Error(), "parse config: wrong permissions") {
			t.Errorf("unexpected error message: got %v", err)
		}
	}

	// Legacy sendxmpp formats.
	cfg, err = parseConfig("testdata/config003")
	if err != nil {
		t.Fatalf("Failed to parse config: %v", err)
	}
	if cfg.username != "user@example.com" {
		t.Errorf("Expected username 'user@example.com', got '%s'", cfg.username)
	}
	if cfg.password != "hunter2" {
		t.Errorf("Expected password 'hunter2', got '%s'", cfg.password)
	}
	if cfg.jserver != "example.com" {
		t.Errorf("Expected jserver 'example.com', got '%s'", cfg.jserver)
	}
	cfg, err = parseConfig("testdata/config004")
	if err != nil {
		t.Fatalf("Failed to parse config: %v", err)
	}
	if cfg.username != "user@example.com" {
		t.Errorf("Expected username 'user@example.com', got '%s'", cfg.username)
	}
	if cfg.jserver != "xmpp.example.com" {
		t.Errorf("Expected jserver 'xmpp.example.com', got '%s'", cfg.jserver)
	}
	if cfg.password != "hunter2" {
		t.Errorf("Expected password 'hunter2', got '%s'", cfg.password)
	}
	if cfg.jserver != "xmpp.example.com" {
		t.Errorf("Expected jserver 'xmpp.example.com', got '%s'", cfg.jserver)
	}
}
