package main

import (
	"flag"
	"fmt"
	wukong "github.com/huichen/wukong/engine"
	"github.com/huichen/wukong/types"
	"os"
	"os/signal"
)

/**
  wukongd 基于 wukong 实现，内置一个 http server. 和一个启动配置文件

  * 支持字符串索引

  多实例部署可直接启动多个实例，http 客户端来实现索引的 hash-sharding 以及 查询汇总

*/

var (
	searcher    = wukong.Engine{}
	confile     = flag.String("c", "wukongd.conf", "specify the config file")
	test_conf   = flag.String("t", "", "test specified config file")
	showVersion = flag.Bool("v", false, "display version")
)

func main() {
	flag.Parse()

	var err error
	// version
	if *showVersion {
		printVersion()
		return
	}
	fmt.Println(*test_conf)
	// check config
	if len(*test_conf) > 0 {
		_, err := loadConfig(*test_conf)
		if err != nil {
			fmt.Printf("check config file %s failed: %s.\n", *test_conf, err)
			return
		}
		fmt.Printf("check config file %s succeed.\n", *test_conf)
		return
	}
	// main
	config, err = loadConfig(*confile)
	if err != nil {
		fmt.Printf("check config file %s failed: %v\n", *confile, err)
		return
	}
	// init logger
	// init engine
	options := types.RankOptions{
		OutputOffset: config.Engine.OutputOffset,
		MaxOutputs:   config.Engine.MaxOutput,
	}
	searcher.Init(types.EngineInitOptions{
		SegmenterDictionaries: config.Engine.Dictionary,
		StopTokenFile:         config.Engine.Stoptoken,
		IndexerInitOptions: &types.IndexerInitOptions{
			IndexType: config.Engine.IndexType,
		},
		NumShards:               config.Engine.ShardsNum,
		DefaultRankOptions:      &options,
		UsePersistentStorage:    config.Engine.Persistent,
		PersistentStorageFolder: config.Engine.PersistentFolder,
		PersistentStorageShards: config.Engine.PersistentShardsNum,
	})
	searcher.FlushIndex()
	fmt.Println("indexed:", searcher.NumDocumentsIndexed())
	// init http
	err = startHttp(config.Server.Addr)
	if err != nil {
		panic(err)
	}

	fmt.Println("server started.")
	ch := make(chan os.Signal, 1)
	signal.Notify(ch, os.Interrupt)
	fmt.Println("received signal: ", <-ch, " stopping...")
	stopHttp()
	searcher.Close()
	fmt.Println("stopped.")
}
