package vastxml

import (
	"encoding/xml"
	"ssp/constants"
	"ssp/logger"
	"ssp/redisClient"
	"ssp/vastxmlstructs"
	"strings"
	"time"
)

func SaveVastXml(adm string, key string, redisclient *redisClient.RedisClient) {
	xmlS := &vastxmlstructs.VastTypes{}
	decoder := xml.NewDecoder(strings.NewReader(adm))
	decoder.Strict = false

	if strings.Contains(adm, `version="2.0"`) {
		if strings.Contains(adm, `<Linear>`) && strings.Contains(adm, `<InLine>`) {
			decoder.Decode(&xmlS.VAST2)
		} else if strings.Contains(adm, `<Linear>`) && strings.Contains(adm, `<Wrapper>`) {
			decoder.Decode(&xmlS.WVAST2)
		}
	} else if strings.Contains(adm, `version="3.0"`) {

		if strings.Contains(adm, `<Linear`) && strings.Contains(adm, `<InLine>`) {
			decoder.Decode(&xmlS.VAST3)
		} else if strings.Contains(adm, `<Linear`) && strings.Contains(adm, `<Wrapper>`) {
			decoder.Decode(&xmlS.WVAST3)
		}
	} else if strings.Contains(adm, `version="4.0"`) {
		if strings.Contains(adm, `<Linear`) && strings.Contains(adm, `<InLine>`) {
			decoder.Decode(&xmlS.VAST4)
		} else if strings.Contains(adm, `<Linear`) && strings.Contains(adm, `<Wrapper`) {
			decoder.Decode(&xmlS.WVAST4)
		}
	} else if strings.Contains(adm, `version="4.1"`) {
		if strings.Contains(adm, `<Linear`) && strings.Contains(adm, `<InLine>`) {
			decoder.Decode(&xmlS.VAST41)
		} else if strings.Contains(adm, `<Linear`) && strings.Contains(adm, `<Wrapper`) {
			decoder.Decode(&xmlS.WVAST41)
		}
	}

	err := redisclient.SetKey(key, xmlS, time.Minute*constants.RedisExpInMin)
	if err != nil {
		logger.Log.Println("Error in setting redis key: ", err.Error())
	}
	return
}
