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")

	zn := outputData.Zone_details

	if outputData.Tag_type == "video" || outputData.Tag_type == "audio" {

		vast := helper.GetUrlParam(outputData.R, "vast")
		if vast != "" {

			protocal := 0
			lineatity := 0
			ad_type := 0

			switch vast {

			case "vast2":
				protocal = 1
				lineatity = 1
			case "vast3":
				protocal = 2
				lineatity = 1
			case "vast4":
				protocal = 3
				lineatity = 1
			case "vast4_1":
				protocal = 4
				lineatity = 1

			case "vast2_wrapper":
				protocal = 1
				lineatity = 2
			case "vast3_wrapper":
				protocal = 2
				lineatity = 2
			case "vast4_wrapper":
				protocal = 3
				lineatity = 2
			case "vast4_1_wrapper":
				protocal = 4
				lineatity = 2
			case "daast_1":
				protocal = 4
				lineatity = 1
				ad_type = 1
			}

			extraQuery_join = " INNER JOIN " + table_prefix + "djaxbanner_vast_element as vast on d.bannerid = vast.banner_id "
			extraQuery_where = " AND vast.vast_type = %d AND  vast.get_third_internal_type = %d "
			if ad_type == 1 {
				extraQuery_where = extraQuery_where + " AND vast.ad_type = 1"
			}

			extraQuery_where = fmt.Sprintf(extraQuery_where, protocal, lineatity)
		}

	}

	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 != 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 != 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 != NULL,c.expire_time, '')  AS expire_time, c.revenue_type AS revenue_type, c.ecpm_enabled AS ecpm_enabled, IF(c.ecpm != NULL,c.ecpm, 0.00) AS ecpm, IF(ct.status != 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 + "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

	adQuery = fmt.Sprintf(adQuery, zn.Zoneid)

	fmt.Println("adquery", adQuery)

	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 budget_status=0  AND d.campaignid = c.campaignid AND m.clientid = c.clientid"

	adQuery = fmt.Sprintf(adQuery, ad_id)

	fmt.Println("getadquery", adQuery)

	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)

		fmt.Println("ad Select From Quesry")

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

	}
	defer rows.Close()
	return adDetails

}
