package ads

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

	config "alpha/configuration"
	"alpha/db"
	"database/sql"
	"strconv"
)

var redisClients = redisClient.Initialize()

func InternalAdSelect(outputData *structure.OutputData) *sql.Rows {
	var extraQuery_join string
	var extraQuery_where string
	table_prefix := config.GetConfig("prefix", "table")

	// Video / Audio vast handling
	if outputData.Tag_type == "video" || outputData.Tag_type == "audio" {
		vast := helper.GetUrlParam(outputData.R, "vast")
		adDuration := helper.GetUrlParam(outputData.R, "adDuration")

		if vast != "" {
			protocal, lineatity, ad_type := 0, 0, 0

			switch vast {
			case "vast2":
				protocal, lineatity = 1, 1
			case "vast3":
				protocal, lineatity = 2, 1
			case "vast4":
				protocal, lineatity = 3, 1
			case "vast4_1":
				protocal, lineatity = 4, 1
			case "vast2_wrapper":
				protocal, lineatity = 1, 2
			case "vast3_wrapper":
				protocal, lineatity = 2, 2
			case "vast4_wrapper":
				protocal, lineatity = 3, 2
			case "vast4_1_wrapper":
				protocal, lineatity = 4, 2
			case "daast_1":
				protocal, lineatity, ad_type = 4, 1, 1
			}

			extraQuery_join = " INNER JOIN " + table_prefix + "djaxbanner_vast_element as vast ON d.bannerid = vast.banner_id "
			extraQuery_where = fmt.Sprintf(" AND vast.vast_type = %d AND vast.get_third_internal_type = %d", protocal, lineatity)

			if ad_type == 1 {
				extraQuery_where += " AND vast.ad_type = 1"
			}

			if adDuration != "" {
				if dur, err := strconv.Atoi(adDuration); err == nil {
					extraQuery_where += fmt.Sprintf(" AND vast.vast_video_duration <= %d", dur)
				}
			}
		} else {
			extraQuery_join = " INNER JOIN " + table_prefix + "djaxbanner_vast_element as vast ON d.bannerid = vast.banner_id "

			if adDuration != "" {
				if dur, err := strconv.Atoi(adDuration); err == nil {
					extraQuery_where = fmt.Sprintf(" AND vast.vast_video_duration <= %d", dur)
				}
			}
		}
	}

	// Placement handling
	Placement := helper.GetUrlParam(outputData.R, "placement")
	adType := 0
	switch Placement {
	case "preroll":
		adType = 1
	case "midroll":
		adType = 2
	case "postroll":
		adType = 3
	}

	WH := ""
	if adType > 0 {
		WH = fmt.Sprintf(" AND d.placement_type = %d ", adType)
	}

	// Final Query
	adQuery := "SELECT d.bannerid AS ad_id, d.campaignid AS placement_id,  c.clientid AS clientid, d.status AS status, d.width AS width, " +
		"IF(d.ext_bannertype IS NOT NULL, d.ext_bannertype, '') AS ext_bannertype, d.height AS height, d.storagetype AS type, d.contenttype AS contenttype, " +
		"d.weight AS weight, d.adserver AS adserver, d.block AS block_ad, d.capping AS cap_ad, d.session_capping AS session_cap_ad, " +
		"d.compiledlimitation AS compiledlimitation, IF(d.acl_plugins IS NOT NULL, d.acl_plugins, '') AS acl_plugins, d.alt_filename AS alt_filename, " +
		"az.priority AS priority, az.priority_factor AS priority_factor, az.to_be_delivered AS to_be_delivered, c.campaignid AS campaign_id, " +
		"c.priority AS campaign_priority, c.weight AS campaign_weight, c.companion AS campaign_companion, c.block AS block_campaign, " +
		"c.capping AS cap_campaign, c.session_capping AS session_cap_campaign, c.show_capped_no_cookie AS show_capped_no_cookie, " +
		"c.clientid AS client_id, IF(c.expire_time IS NOT NULL, c.expire_time, '') AS expire_time, c.revenue_type AS revenue_type, " +
		"c.ecpm_enabled AS ecpm_enabled, IF(c.ecpm IS NOT NULL, c.ecpm, 0.00) AS ecpm, IF(ct.status IS NOT NULL, ct.status, 0) AS tracker_status " +
		"FROM " + table_prefix + "banners AS d " +
		"JOIN " + table_prefix + "ad_zone_assoc AS az ON (d.bannerid = az.ad_id) JOIN " + table_prefix + "zones AS z ON z.zoneid = az.zone_id " +
		"JOIN " + table_prefix + "campaigns AS c ON (c.campaignid = d.campaignid) " +
		"LEFT JOIN " + table_prefix + "clients AS cl ON (cl.clientid = c.clientid) " +
		"LEFT JOIN " + table_prefix + "campaigns_trackers AS ct ON (ct.campaignid = c.campaignid) " +
		extraQuery_join + " WHERE az.zone_id = %d AND d.status <= 0 AND c.status <= 0 " + extraQuery_where + WH

	Zonesrt := helper.GetUrlParam(outputData.R, "zoneid")
	ZoneID, _ := strconv.Atoi(Zonesrt)
	adQuery = fmt.Sprintf(adQuery, ZoneID)

	rows, err := db.DbQuery(adQuery)
	if err != nil {
		fmt.Println("Failed to run query", err)
	}

	return rows
}


func GetAd(ad_id int, adDetails AdDetails) AdDetails {

	ad_id_str := strconv.Itoa(ad_id)

	redisClients.GetKey("adid"+ad_id_str, &adDetails)

	if adDetails.Ad_id != 0 {

		return adDetails
	}

	table_prefix := config.GetConfig("prefix", "table")

	adQuery := "SELECT d.bannerid AS ad_id, d.campaignid AS placement_id, d.status AS status, d.description AS name, d.storagetype AS type, d.contenttype AS contenttype, d.pluginversion AS pluginversion, d.filename AS filename, d.imageurl AS imageurl, d.htmltemplate AS htmltemplate, d.htmlcache AS htmlcache, d.width AS width, d.height AS height, d.weight AS weight, d.seq AS seq, d.target AS target, d.url AS url, d.alt AS alt, d.statustext AS statustext, d.bannertext AS bannertext, d.adserver AS adserver, d.block AS block_ad, d.capping AS cap_ad, d.session_capping AS session_cap_ad, d.compiledlimitation AS compiledlimitation, d.acl_plugins AS acl_plugins, d.prepend AS prepend, d.append AS append, d.bannertype AS bannertype, d.alt_filename AS alt_filename, d.alt_imageurl AS alt_imageurl, d.alt_contenttype AS alt_contenttype, d.parameters AS parameters, d.transparent AS transparent, IF(d.ext_bannertype != NULL,d.ext_bannertype, '') as ext_bannertype, d.iframe_friendly AS iframe_friendly, c.campaignid AS campaign_id, c.block AS block_campaign, c.capping AS cap_campaign, c.session_capping AS session_cap_campaign, c.show_capped_no_cookie AS show_capped_no_cookie, m.clientid AS client_id, c.clickwindow AS clickwindow, c.viewwindow AS viewwindow, m.advertiser_limitation AS advertiser_limitation, m.agencyid AS agency_id, c.status AS campaign_status FROM " + table_prefix + "banners AS d, " + table_prefix + "campaigns AS c, " + table_prefix + "clients AS m WHERE d.bannerid=%d  AND d.campaignid = c.campaignid AND m.clientid = c.clientid"

	adQuery = fmt.Sprintf(adQuery, ad_id)

	rows, err := db.DbQuery(adQuery)

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

	for rows.Next() {

		err = helper.Scan(&adDetails, rows)

		redisClients.SetKey("adid"+ad_id_str, adDetails)

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

	}
	defer rows.Close()
	return adDetails

}
