package analytics

import (
	"fmt"

	elastic "gopkg.in/olivere/elastic.v3"
)

//Elasticsearch stores configuration related to the AWS elastic cache isntance.
type Elasticsearch struct {
	URL       string
	IndexName string
	DocType   string
	client    *elastic.Client
}

//Initialize initializes the analytics engine.
func (e *Elasticsearch) Initialize() error {
	client, err := elastic.NewSimpleClient(elastic.SetURL(e.URL))
	if err != nil {
		return err
	}

	e.client = client

	s := e.client.IndexExists(e.IndexName)
	exists, err := s.Do()
	if err != nil {
		return err
	}

	if !exists {
		s := e.client.CreateIndex(e.IndexName)
		_, err := s.Do()
		if err != nil {
			return err
		}
	}

	return nil
}

//SendAnalytics is used to send the data to the analytics engine.
func (e *Elasticsearch) SendAnalytics(data string) error {
	fmt.Println(data)
	_, err := e.client.Index().Index(e.IndexName).Type(e.DocType).BodyJson(data).Do()
	if err != nil {
		return err
	}
	return nil
}
