package ads

import (
	"alpha/adDelivery/structure"
	"net/http"

	//~ "fmt"
	"alpha/adDelivery/capping"
	"alpha/adDelivery/deliveryLimitation"
	"alpha/adDelivery/helper"
)

func CheckAdCriteria(r *http.Request, ads_info map[string][]AdLinkedZone, zninfo structure.ZoneDetails, house_ad bool) ([]AdLinkedZone, string) {

	var finalAds []AdLinkedZone
	var reTargetingAds []AdLinkedZone
	var campaign_type string
	campaigns := [4]string{"xAds", "lAds", "eAds", "ads"}

	validate_campaign := make(map[int]int)

	for _, i := range campaigns {

		c_ads := ads_info[i]

		for _, banner := range c_ads {

			if validate_campaign[banner.Placement_id] == 1 {

				finalAds = append(finalAds, banner)
				continue
			}

			if validate_campaign[banner.Placement_id] == 2 {
				continue
			}

			if (house_ad == false && banner.Advertiser_payment_type == 3) || (house_ad == true && banner.Advertiser_payment_type != 3) {
				continue
			}

			ChZoneCap := capping.CheckCaping(r, zninfo.Zoneid, zninfo.Block, zninfo.Capping, zninfo.Session_capping, "zone")
			if ChZoneCap == false {
				continue
			}

			ChBannerCap := capping.CheckCaping(r, banner.Ad_id, banner.Block_ad, banner.Cap_ad, banner.Session_cap_ad, "banner")
			if ChBannerCap == false {
				continue
			}

			ChCampaignCap := capping.CheckCaping(r, banner.Campaign_id, banner.Block_campaign, banner.Cap_campaign, banner.Session_cap_campaign, "campaign")
			if ChCampaignCap == false {
				continue
			}

			ChDeliveyLimit := deliveryLimitation.CheckAcls(banner.Compiledlimitation, zninfo, r)

			if ChDeliveyLimit == true {
				validate_campaign[banner.Placement_id] = 1
			} else {
				validate_campaign[banner.Placement_id] = 2
			}

			if ChDeliveyLimit == false {
				continue
			}

			if CookieValue(r, "RETAG_"+helper.IntToString(banner.Clientid)) == "1" {
				reTargetingAds = append(reTargetingAds, banner)
			}

			finalAds = append(finalAds, banner)

		}

		if len(finalAds) > 0 {
			campaign_type = i
			break
		}

	}

	if len(reTargetingAds) > 0 {
		finalAds = reTargetingAds
	}

	return finalAds, campaign_type

}
