package tests

import (
	"bytes"
	"os"
	"path/filepath"
	"testing"

	"notabug.org/Umnik/GoAndroidSDK/v2/components/sdk/buildTools/zipalign"
)

func newZipalign(t *testing.T) *zipalign.Zipalign {
	t.Helper()
	za, err := zipalign.NewZipalignLastVersion(*newSdk(t, t.Name()))
	if !testErr(t, t.Name(), err) {
		return nil
	}
	return za
}

func TestCheckAligment(t *testing.T) {
	t.Parallel()
	za := newZipalign(t)
	out, err := za.CheckAlign(goodApkFile(), "4", true, true)
	if !testErr(t, t.Name(), err) {
		return
	}
	for _, line := range bytes.Split(out, []byte("/n")) {
		if bytes.Contains(line, []byte("Verifying alignment of")) ||
			bytes.Contains(line, []byte("(OK")) ||
			bytes.Contains(line, []byte("Verification succesful")) {
			t.Logf("%s", line)
		} else {
			t.Errorf("Zipalign failed: %s", line)
		}
	}
}

func TestDoAligment(t *testing.T) {
	t.Parallel()
	za := newZipalign(t)
	gfTmp, err := os.CreateTemp("", "zipalign-*") // чтобы не повредить тестовый файл
	if !testErr(t, t.Name(), err) {
		return
	}
	defer removeOsFile(t, t.Name(), gfTmp.Name())
	if !makeCopy(t, t.Name(), gfTmp, goodApkFile()) {
		return
	}
	outFile := filepath.Join(os.TempDir(), "out.apk")
	defer removeOsFile(t, t.Name(), outFile)
	out, err := za.DoAlign(gfTmp.Name(), outFile, "4", false, true, true)
	if !testErr(t, t.Name(), err) {
		return
	}
	if !bytes.Contains(out, []byte("Verification succesful")) {
		t.Errorf("Aligment fails with: %s", out)
	}
}
