package sensitivefilter

import (
	"bufio"
	"bytes"
	"fmt"
	"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
}

func IsNickValid(nick string) bool {
	if len(nick) == 0 {
		return false
	}

	content := []rune(nick)
	terms := ahoMachine.MultiPatternSearch(content, false)
	for _, t := range terms {
		fmt.Printf("%d %s\n", t.Pos, string(t.Word))
	}
	return len(terms) == 0
}

// 检查敏感字是否存在
func CheckValidIsExist(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
	}

	//// 手机号
	//phoneRegex := regexp.MustCompile(`(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}`)
	//if phoneRegex.MatchString(content) {
	//	content = phoneRegex.ReplaceAllString(content, "***********")
	//	isExist = 1
	//}
	//
	//// 手机号
	//mailRegex := regexp.MustCompile(`\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*`)
	//if mailRegex.MatchString(content) {
	//	content = mailRegex.ReplaceAllString(content, "***********")
	//	isExist = 1
	//}

	// 检测
	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
}
