package cjlookup import ( "fmt" "strconv" "strings" query "github.com/tgckpg/golifehk/query" utils "github.com/tgckpg/golifehk/utils" "golang.org/x/exp/slices" ) type QueryResult struct { Lang string Error error Query *query.QueryObject } func writeCCharInfo(sb *strings.Builder, cc *CChar) { sb.WriteString(getCUHARTSUrlForChar(cc.Face)) sb.WriteString(" ") utils.WriteMDv2Text(sb, cc.JyutPing) if cc.YiDukJam != nil { sb.WriteString("\n") utils.WriteMDv2Text(sb, "異讀: ") utils.WriteMDv2Text(sb, strings.Join(*cc.YiDukJam, " ")) } sb.WriteString("\n") utils.WriteMDv2Text(sb, "倉: ") utils.WriteMDv2Text(sb, cc.CangJie) sb.WriteString("\n") utils.WriteMDv2Text(sb, "同音字:") slices.SortFunc(*cc.TungJamZi, func(a, b *CChar) int { switch { case a.Face < b.Face: return -1 case a.Face > b.Face: return 1 default: return 0 } }) for i, cchar := range *cc.TungJamZi { sb.WriteString(" ") utils.WriteMDv2Text(sb, cchar.Face) utils.WriteMDv2Text(sb, strconv.Itoa(i+1)) } } func (this QueryResult) Message() (string, error) { if this.Error != nil { return "", this.Error } if this.Query == nil { panic("Query is nil") } sb := strings.Builder{} q := *this.Query argv := *q.SearchTerms args := len(argv) if len(*q.Results) == 0 { terms := make([]string, args, len(*q.SearchTerms)) for i, term := range *q.SearchTerms { terms[i] = term.Org } return "", fmt.Errorf("Not Found: \"%s\"", strings.Join(terms, "\", \"")) } slices.SortFunc(*q.Results, func(a, b query.ISearchable) int { aa := a.(*CJyutPing) bb := b.(*CJyutPing) switch { case aa.Ref.Face < bb.Ref.Face: return -1 case aa.Ref.Face > bb.Ref.Face: return 1 default: return 0 } }) if utils.IsASCIIAlnum(argv[0].Value) { if args == 1 { for i, entry := range *q.Results { cjp := any(entry).(*CJyutPing) sb.WriteString(" ") utils.WriteMDv2Text(&sb, cjp.Ref.Face) utils.WriteMDv2Text(&sb, strconv.Itoa(i+1)) } } else if args == 2 { var err error x, err := strconv.Atoi(argv[1].Value) if err != nil { return "", fmt.Errorf("Invalid index: %s", argv[1].Org) } if 0 < x { for i, entry := range *q.Results { cjp := any(entry).(*CJyutPing) if (i + 1) == x { writeCCharInfo(&sb, cjp.Ref) } } } } } else { cjp := any((*q.Results)[0]).(*CFace) if args == 1 { writeCCharInfo(&sb, cjp.Ref) } else if args == 2 { var err error x, err := strconv.Atoi(argv[1].Value) if err != nil { return "", fmt.Errorf("Invalid index: %s", argv[1].Org) } tjz := (*(*cjp.Ref).TungJamZi)[x-1] if tjz != nil { writeCCharInfo(&sb, tjz) } } } return sb.String(), nil }