package ads_external

import (
	"alpha/adDelivery/helper"
	"alpha/redisClient"
	"fmt"

	config "alpha/configuration"
	"alpha/db"

	"github.com/elliotchance/phpserialize"
)

var redisClients = redisClient.Initialize()

var adQuery string
var table_prefix = config.GetConfig("prefix", "table")

func getZoneOpenRtbParams(zone_id int) AdExchangeZone {

	zoneExtra := AdExchangeZone{}

	zone_id_str := helper.IntToString(zone_id)

	redisClients.GetKey("zonexchange"+zone_id_str, &zoneExtra)

	if zoneExtra.Zoneid == 0 {

		adQuery = "SELECT * FROM " + table_prefix + "exchange_zone_assoc WHERE zoneid = %d"
		adQuery = fmt.Sprintf(adQuery, zone_id)
		rows, err := db.DbQuery(adQuery)

		for rows.Next() {

			err = helper.Scan(&zoneExtra, rows)
			fmt.Println("Getting zonexchange details from Mysql")
			redisClients.SetKey("zonexchange"+zone_id_str, zoneExtra)

			if err != nil {
				fmt.Println("Failed to run query", err)
			}
			break
		}
		defer rows.Close()
	} else {
		fmt.Println("Getting zonexchange details from redis")
	}

	return zoneExtra

}

type AdminConfig struct {
	Buffer_amount    float64
	Rtb_responsetime int
}

func getAdminDetails() (float64, int) {

	admin_config := AdminConfig{}

	redisClients.GetKey("admin_config", &admin_config)
	value := redisClients.IfExists("admin_config")
	fmt.Println("value", value)

	// if admin_config.Rtb_responsetime == 0 {

	if value == 0 {
		adQuery = "SELECT ssp_second_buffer, rtb_response_time FROM " + table_prefix + "dj_admin_configuration"
		rows, err := db.DbQuery(adQuery)

		for rows.Next() {

			err = helper.Scan(&admin_config, rows)
			fmt.Println("Getting admin_config details from mysql")
			redisClients.SetKey("admin_config", admin_config)

			if err != nil {
				fmt.Println("Failed to run query", err)
			}
			break
		}
		defer rows.Close()
	} else {
		fmt.Println("Getting admin_config details from redis")
	}

	return admin_config.Buffer_amount, admin_config.Rtb_responsetime

}

func getZonePublisherDetails(zone_id int, affiliateid int) SiteObjects__pub {

	pub_details := SiteObjects__pub{}
	zone_id_str := helper.IntToString(zone_id)

	redisClients.GetKey("zonepub"+zone_id_str, &pub_details)

	if pub_details.Id == "" {

		adQuery = "SELECT CONVERT(affiliateid,CHAR) as Id,name as Name, website as Domain  FROM " + table_prefix + "affiliates WHERE affiliateid = %d"
		adQuery = fmt.Sprintf(adQuery, affiliateid)
		rows, err := db.DbQuery(adQuery)

		for rows.Next() {
			fmt.Println("Getting zonepub details from mysql")
			err = helper.Scan(&pub_details, rows)
			redisClients.SetKey("zonepub"+zone_id_str, pub_details)
			if err != nil {
				fmt.Println("Failed to run query", err)
			}
			break
		}
		defer rows.Close()
	} else {
		fmt.Println("Getting zonepub details from redis")
	}

	return pub_details
}

func getZoneMatechedDeals(zone_id int, width int, height int) []DealsDetails {

	zone_id_str := helper.IntToString(zone_id)

	cache_deals := Cache_DealsDetails{}

	matchedDeals := []DealsDetails{}

	redisClients.GetKey("is_deals"+zone_id_str, &cache_deals)

	if cache_deals.In == 1 {

		matchedDeals = cache_deals.MatchedDeals
		fmt.Println("Getting is_deals details from redis")

	} else {

		Query := "SELECT dealid, dealid_token,  auction_type, floor_price, zones, adsize ,whitelist FROM " + table_prefix + "dealid WHERE is_pause= 0 AND is_expire =0 AND is_delete=0 "
		rows, err := db.DbQuery(Query)

		for rows.Next() {

			deals := DealsDetails{}

			err = helper.Scan(&deals, rows)

			if err != nil {
				fmt.Println("Failed to run query", err)
			} else {

				var dealZones map[interface{}]interface{}
				phpserialize.Unmarshal([]byte(deals.Zones), &dealZones)

				for _, zone_id := range dealZones {

					if zone_id == zone_id_str {

						var dealSizes map[interface{}]interface{}
						phpserialize.Unmarshal([]byte(deals.Adsize), &dealSizes)

						for _, zone_id := range dealZones {

							if zone_id == zone_id_str {

								matchedDeals = append(matchedDeals, deals)
								break
							}
						}
					}
				}
			}
		}

		defer rows.Close()
		redisClients.SetKey("is_deals"+zone_id_str, Cache_DealsDetails{In: 1, MatchedDeals: matchedDeals})
		fmt.Println("Getting is_deals details from mysql")
	}

	return matchedDeals
}

func getZoneBuyerDetails(zone_id int, ssp_buyer string) []ExchangeDetails {

	var buyers map[interface{}]interface{}
	phpserialize.Unmarshal([]byte(ssp_buyer), &buyers)

	buyer_details := []ExchangeDetails{}

	for key, buyerid := range buyers {
		fmt.Println("key", key)
		fmt.Println("buyer_id", buyerid)
		buyer_detail := ExchangeDetails{}

		redisClients.GetKey(fmt.Sprintf("buyer%s", buyerid), &buyer_detail)

		if buyer_detail.Exchange_id != 0 {
			fmt.Println("Getting buyer details from redis")
			buyer_details = append(buyer_details, buyer_detail)

			continue
		}

		Colnames := "exchange_id as Exchange_id ,exchange_name as Exchange_name, open_rtb_version as Open_rtb_version , status as Status, ping_url as Ping_url , auction_currency as Auction_currency , auction_type as Auction_type , digital_signature as Digital_signature, gzip as Gzip"
		adQuery = "SELECT " + Colnames + " FROM " + table_prefix + "dj_ad_exchange WHERE exchange_id = %s"

		adQuery = fmt.Sprintf(adQuery, buyerid)
		rows, err := db.DbQuery(adQuery)

		for rows.Next() {

			err = helper.Scan(&buyer_detail, rows)

			if err != nil {
				fmt.Println("Failed to run query", err)
			} else {
				fmt.Println("Getting buyer details from mysql")
				redisClients.SetKey(fmt.Sprintf("buyer%s", buyerid), buyer_detail)
				buyer_details = append(buyer_details, buyer_detail)
			}

		}
		defer rows.Close()
	}

	return buyer_details

}
