package es

import (
	"context"
	"fmt"
	"github.com/olivere/elastic"
	"iot_manager_service/config"
	"log"
	"os"
	"time"
)

type es struct {
}

var Es es
var Client *elastic.Client

func (e *es) InitES() {
	errLog := log.New(os.Stdout, "APP", log.LstdFlags)
	url := config.Instance().Es.URL
	client, err := elastic.NewClient(elastic.SetErrorLog(errLog))
	elastic.SetURL(url)
	if err != nil {
		//todo 初始化错误处理
		panic(err)
	}
	Client = client
	//启动定时删除
	go delTicker()
}

// 定时器
func delTicker() {
	ticker := time.Tick(15 * 24 * time.Hour)
	for range ticker {
		indexName := time.Now().Add(-15 * 24 * time.Hour).Format("2006-01-02")
		delIndex(indexName)
	}
}

// DelIndex 删除索引
func delIndex(indexName string) {
	res, err := Client.DeleteIndex(indexName).Do(context.Background())
	if err != nil {
		fmt.Printf("res:%v\nerror:%v\n", res, err)
	}
}
