package mapping

import (
	"fmt"

	log "github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	"iwarma.ru/console/correlator/config"
)

type Mapping struct {
	Url  string
	File string
	Type string
}

const (
	MappingComponent = "component"
	MappingIndex     = "index"
)

func UpdateMapping(mapping *[]Mapping) error {

	for _, cur := range *mapping {
		url := fmt.Sprintf("%v/%v", viper.GetString(config.ElasticUrl), cur.Url)

		cl := log.WithFields(log.Fields{"url": url, "file": cur.File, "type": cur.Type})

		if cur.Type == MappingComponent {
			component, err := ReadComponentFromFile(cur.File)
			if err != nil {
				return err
			}

			ok, err := CheckComponentUpdate(url, component)
			if err != nil {
				return err
			}

			if ok {
				cl.Infof("Need to update component")
				err = UpdateComponent(url, component)
				if err != nil {
					cl.Error(err)
					return err
				}
			} else {
				cl.Infof("NO need to update component")
			}
		} else if cur.Type == MappingIndex {
			index, err := ReadIndexFromFile(cur.File)
			if err != nil {
				return err
			}

			ok, err := CheckIndextUpdate(url, index)
			if err != nil {
				return err
			}

			if ok {
				cl.Infof("Need to update component")
				err = UpdateIndex(url, index)
				if err != nil {
					cl.Error(err)
					return err
				}
			} else {
				cl.Infof("NO need to update index")
			}
		} else {
			return fmt.Errorf("got unknown mapping type: %v", cur.Type)
		}
	}

	return nil
}
