/*
	This will attempt to delete a RR in a DNS zone file.

	Delete("wit.com", "test.wit.com", "1.1.1.1"
*/

package cloudflare

import (
	"go.wit.com/log"
	"os"
)

func Delete(zone string, hostname string, value string) (bool, string) {
	log.Info(INFO, "Delete() START", zone, hostname, value)
	key := os.Getenv("CF_API_KEY")
	email := os.Getenv("CF_API_EMAIL")

	if key == "" {
		log.Log(WARN, "Delete() MISSING environment variable CF_API_KEY")
		return false, ""
	}
	if email == "" {
		log.Log(WARN, "Delete() MISSING environment variable CF_API_EMAIL")
		return false, ""
	}

	GetZones(key, email)
	var z *ConfigT
	for d, v := range Config {
		log.Log(INFO, "Delete() zone =", d, "value =", v)
		if zone == d {
			z = Config[zone]
			log.Log(INFO, "Delete() FOUND ZONE", zone, "ID =", z.ZoneID)
		}
	}
	if z == nil {
		log.Log(WARN, "Delete() COULD NOT FIND ZONE", zone)
		return false, ""
	}
	log.Log(INFO, "Delete() FOUND ZONE", z)

	records := GetZonefile(z)
	for i, record := range records.Result {
		if record.Name == hostname {
			log.Log(INFO, "Delete() FOUND hostname:", i, record.ID, record.Type, record.Name, record.Content)
		}
		if record.Content == value {
			log.Log(INFO, "Delete() FOUND CONTENT:", i, record.ID, record.Type, record.Name, record.Content)
			log.Log(INFO, "Delete() DO THE ACTUAL cloudflare DELETE here")
			result := doCurlDelete(key, email, z.ZoneID, record.ID)
			pretty, _ := FormatJSON(result)
			log.Log(INFO, "Delete() result =", pretty)
			return true, pretty
		}
	}

	log.Log(WARN, "Delete() NEVER FOUND cloudflare value:", value)
	return false, ""
}