// Package inject provides script and style injection utilities.
package inject

import (
	"encoding/json"
	"html"
	"strings"
)

// Head injects a string before the closing head tag.
func Head(html, s string) string {
	return strings.Replace(html, "</head>", "  "+s+"\n  </head>", 1)
}

// Body injects a string before the closing body tag.
func Body(html, s string) string {
	return strings.Replace(html, "</body>", "  "+s+"\n  </body>", 1)
}

// Script returns an script.
func Script(src string) string {
	return `<script src="` + html.EscapeString(src) + `"></script>`
}

// ScriptInline returns an inline script.
func ScriptInline(s string) string {
	return `<script>` + s + `</script>`
}

// Style returns an style.
func Style(href string) string {
	return `<link rel="stylesheet" href="` + html.EscapeString(href) + `">`
}

// StyleInline returns an inline style.
func StyleInline(s string) string {
	return `<style>` + s + `</style>`
}

// Comment returns an html comment.
func Comment(s string) string {
	return "<!-- " + html.EscapeString(s) + " -->"
}

// Segment inline script with key.
func Segment(key string) string {
	return ScriptInline(`
  !function(){var analytics=window.analytics=window.analytics||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("Segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","reset","group","track","ready","alias","debug","page","once","off","on"];analytics.factory=function(t){return function(){var e=Array.prototype.slice.call(arguments);e.unshift(t);analytics.push(e);return analytics}};for(var t=0;t<analytics.methods.length;t++){var e=analytics.methods[t];analytics[e]=analytics.factory(e)}analytics.load=function(t){var e=document.createElement("script");e.type="text/javascript";e.async=!0;e.src=("https:"===document.location.protocol?"https://":"http://")+"cdn.segment.com/analytics.js/v1/"+t+"/analytics.min.js";var n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(e,n)};analytics.SNIPPET_VERSION="4.0.0";
  analytics.load("` + key + `");
  analytics.page();
  }}();
`)
}

// GoogleAnalytics inline script with tracking key.
func GoogleAnalytics(trackingID string) string {
	return ScriptInline(`
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

  ga('create', '` + trackingID + `', 'auto');
  ga('send', 'pageview');
`)
}

// Var injection.
func Var(kind, name string, v interface{}) string {
	b, _ := json.Marshal(v)
	return ScriptInline(kind + ` ` + name + ` = ` + string(b))
}
