package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"os"
)

const template = `// This file was generated by _tools/gen-definitions.go. DO NOT EDIT.

package definition
import "sync"

var %[1]s Emojis
var %[1]sOnce sync.Once

func %[2]s(opts ...EmojisOption) Emojis {
	%[1]sOnce.Do(func() {
		%[1]s = NewEmojis(
			%[3]s,
        )
	})
	m := %[1]s.Clone()
	for _, opt := range opts {
		opt(m)
	}
	return m
}
`

func githubSubCommand(args []string) {
	cmdName := "github"
	cmd := flag.NewFlagSet(cmdName, flag.ExitOnError)
	cmd.Usage = func() {
		_, _ = fmt.Fprintf(cmd.Output(), `Usage of %s:

  Generate input JSON data for emb-structs subcommand from github

`, cmdName)
		cmd.PrintDefaults()
	}

	outputPath := cmd.String("o", "", "output file path(required)")

	if err := cmd.Parse(args); err != nil ||
		len(*outputPath) == 0 {
		usage(cmd.Usage, err)
	}

	bs := getURL("https://api.github.com/emojis")
	var ghNames map[string]string
	abortIfError(json.Unmarshal(bs, &ghNames))

	bs = getURL("https://raw.githubusercontent.com/github/gemoji/master/db/emoji.json")
	var list []map[string]any
	abortIfError(json.Unmarshal(bs, &list))

	getShortNames := func(emoji map[string]any) []string {
		ns := []string{}
		for _, name := range emoji["aliases"].([]any) {
			ns = append(ns, name.(string))
		}
		return ns
	}
	getUnicode := func(emoji map[string]any) []string {
		var ret []string
		for _, r := range emoji["emoji"].(string) {
			ret = append(ret, fmt.Sprintf("%d", r))
		}
		return ret
	}
	getDescription := func(emoji map[string]any) string {
		return emoji["description"].(string)
	}

	embstructmap := make(map[string]any)
	embstructmap["prefix"] = "github"
	embstructmap["types"] = map[string]any{
		"Name":       "string",
		"Unicode":    "[]int32",
		"ShortNames": "[]string",
	}
	var data []any

	for _, emoji := range list {
		var names []string
		for _, n := range getShortNames(emoji) {
			if _, ok := ghNames[n]; len(n) > 0 && ok {
				names = append(names, n)
			}
		}
		if len(names) == 0 {
			continue
		}

		desc := getDescription(emoji)
		uc := getUnicode(emoji)
		data = append(data, map[string]any{
			"Name":       desc,
			"Unicode":    uc,
			"ShortNames": names,
		})

	}

	embstructmap["data"] = data
	jsonData, err := json.MarshalIndent(embstructmap, "", "  ")
	if err != nil {
		abortIfError(err)
	}
	err = os.WriteFile(*outputPath, jsonData, 0644)
	if err != nil {
		abortIfError(err)
	}
}
