package main

import (
	"qfw/util"
)

var CityConfig map[string]interface{}
var AreaGet DFA //敏感词

func initarea() {
	util.ReadConfig("city.json", &CityConfig)
	cp := CityConfig["city"].(map[string]interface{})
	citys := []string{}
	for k, _ := range cp {
		citys = append(citys, k)
	}
	AreaGet = DFA{}
	AreaGet.AddWord(citys...)
}

type DFA struct {
	Link map[string]interface{}
}

func (d *DFA) AddWordAll(haskey bool, keys ...string) {
	if d.Link == nil {
		d.Link = make(map[string]interface{})
	}
	for _, key := range keys {
		nowMap := &d.Link
		for i := 0; i < len(key); i++ {
			kc := key[i : i+1]
			if v, ok := (*nowMap)[kc]; ok {
				nowMap, _ = v.(*map[string]interface{})
			} else {
				newMap := map[string]interface{}{}
				newMap["YN"] = "0"
				(*nowMap)[kc] = &newMap
				nowMap = &newMap
			}
			if i == len(key)-1 {
				(*nowMap)["YN"] = "1"
				if haskey {
					(*nowMap)["K"] = key
				}
			}
		}
	}
}

func (d *DFA) AddWord(keys ...string) {
	d.AddWordAll(false, keys...)
}

//适合一次查找
func (d *DFA) CheckSensitiveWord(src string) (b bool) {
	pos := 0
	nowMap := &d.Link
	for i := 0; i < len(src); i++ {
		word := src[i : i+1]
		nowMap, _ = (*nowMap)[word].(*map[string]interface{})
		if nowMap != nil { // 存在，则判断是否为最后一个
			if pos == 0 {
				pos = i
			}
			if "1" == util.ObjToString((*nowMap)["YN"]) { // 如果为最后一个匹配规则,结束循环，返回匹配标识数
				b = true
				break
			}
		} else {
			nowMap = &d.Link
			if pos > 0 {
				i = pos
				pos = 0
			}
		}
	}
	return
}
