package sensitivefilter

import (
	"bufio"
	"bytes"
	"io"
	"log"
	"os"
	"strings"

	goahocorasick "github.com/anknown/ahocorasick"
)

var (
	ahoMachine *goahocorasick.Machine
)

func ReadRunes(filename string) ([][]rune, error) {
	dict := [][]rune{}

	f, err := os.OpenFile(filename, os.O_RDONLY, 0660)
	if err != nil {
		return nil, err
	}

	r := bufio.NewReader(f)
	for {
		l, err := r.ReadBytes('\n')
		if err != nil || err == io.EOF {
			break
		}
		l = bytes.TrimSpace(l)
		dict = append(dict, bytes.Runes(l))
	}

	return dict, nil
}

func LoadSensitiveWords(filepath string) {

	dict, err := ReadRunes(filepath)
	if err != nil {
		log.Fatalf("LoadSensitiveWords error %v", err)
		return
	}

	m := new(goahocorasick.Machine)
	if err := m.Build(dict); err != nil {
		log.Fatalf("LoadSensitiveWords error %v", err)
		return
	}
	ahoMachine = m
}

//// json敏感字
//type SensitiveWords struct {
//	Id string `json:"id"`
//}
//
//func ReadRunes1(filename string) ([][]rune, error) {
//	dict := [][]rune{}
//
//	items := make([]*SensitiveWords, 0)
//	jsonload.LoadJsonFile(filename, &items)
//
//	// Convert each word to []rune and add to the dictionary
//	for _, v := range items {
//		dict = append(dict, []rune(v.Id))
//	}
//
//	return dict, nil
//}
//
//func LoadSensitiveWords1(filepath string) {
//	dict, err := ReadRunes1(filepath)
//	if err != nil {
//		log.Fatalf("LoadSensitiveWords1 error %v", err)
//		return
//	}
//
//	m := new(goahocorasick.Machine)
//	if err := m.Build(dict); err != nil {
//		log.Fatalf("LoadSensitiveWords1 error %v", err)
//		return
//	}
//	ahoMachine = m
//}

// 检查敏感字是否存在
func ContainsSensitiveWord(content string) bool {
	if len(content) == 0 {
		return false
	}

	contents := []rune(content)
	terms := ahoMachine.MultiPatternSearch(contents, false)
	if len(terms) > 0 {
		return true
	}
	return false
}

// 检查敏感字
func CheckValid(content string) (int, string) {
	isExist := 0
	if len(content) == 0 {
		return isExist, content
	}

	// 检测
	terms := ahoMachine.MultiPatternSearch([]rune(content), false)
	for _, t := range terms {
		//fmt.Printf("%d %s\n", t.Pos, string(t.Word))
		content = strings.Replace(content, string(t.Word), GetAA(len(t.Word)), -1)
		isExist = 1
	}
	return isExist, content
}

func GetAA(len int) string {
	str := ""
	for i := 0; i < len; i++ {
		str += "*"
	}
	return str
}
