package internal

import (
	"bytes"
	"fmt"
	"os"
	"path/filepath"
)

type LanguageService struct{}

func isValidLang(lang string) bool {
	valid := []string{"en", "jp", "cn", "kr"}
	for _, v := range valid {
		if lang == v {
			return true
		}
	}
	return false
}

func (l *LanguageService) GetLanguage(path string) (string, string, error) {
	files, err := os.ReadDir(path)
	if err != nil {
		return "", "", err
	}

	for _, file := range files {
		filePath := filepath.Join(path, file.Name())

		content, err := os.ReadFile(filePath)
		if err != nil {
			continue
		}

		patternToFind := []byte("SpriteOutput/UI/Fonts/RPG_CN.ttf")
		idx := bytes.Index(content, patternToFind)
		if idx == -1 {
			continue
		}

		pattern := []byte("Korean")
		idx = bytes.Index(content, pattern)
		if idx == -1 {
			continue
		}

		// Move to os text language
		idx += 10
		idx += 4
		osText := string(content[idx : idx+2])
		idx += 3 * 4 

		// Move to cn voice language
		idx += 1
		idx += 5
		cnVoice := string(content[idx : idx+2])
		idx += 3 * 2 // skip 2 entries

		// Move to os voice language
		idx += 1
		idx += 5
		osVoice := string(content[idx : idx+2])
		idx += 3 * 5 // skip 5 entries

		// Move to cn text language
		idx += 1
		idx += 4
		cnText := string(content[idx : idx+2])

		textLang := osText
		voiceLang := osVoice
		if !isValidLang(textLang) {
			textLang = cnText
		}
		if !isValidLang(voiceLang) {
			voiceLang = cnVoice
		}

		return textLang, voiceLang, nil
	}

	return "", "", fmt.Errorf("couldn't find file to read language from")
}

func replaceBytes(content []byte, idx int, choice string, param int) int {
	for i := 0; i < param; i++ {
		copy(content[idx:idx+2], []byte(choice))
		idx += 3
	}
	return idx
}

func (l *LanguageService) SetLanguage(path string, text, voice string) (bool, error) {
	files, err := os.ReadDir(path)
	if err != nil {
		return false, err
	}

	for _, file := range files {
		filePath := filepath.Join(path, file.Name())

		content, err := os.ReadFile(filePath)
		if err != nil {
			continue
		}

		patternToFind := []byte("SpriteOutput/UI/Fonts/RPG_CN.ttf")
		idx := bytes.Index(content, patternToFind)
		if idx == -1 {
			continue
		}

		pattern := []byte("Korean")
		idx = bytes.Index(content, pattern)
		if idx == -1 {
			continue
		}

		idx += 10
		idx += 4
		idx = replaceBytes(content, idx, text, 4)
		idx += 1

		idx += 5
		idx = replaceBytes(content, idx, voice, 2)
		idx += 1

		idx += 5
		idx = replaceBytes(content, idx, voice, 5)

		idx += 1

		idx += 4
		_ = replaceBytes(content, idx, text, 2)

		err = os.WriteFile(filePath, content, 0644)
		if err != nil {
			return false, err
		}

		return true, nil
	}

	return false, fmt.Errorf("couldn't find file to patch. Make sure this file is placed in the correct folder")
}
