package twitchstats

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
)

type MixpanelResponse struct {
	Status int
	Error  string
}

type mixpanel struct {
	Client     *http.Client           `json:"-"`
	Event      string                 `json:"event"`
	Properties map[string]interface{} `json:"properties"`
	Verbose    bool                   `json:"-"`
}

func (mp *mixpanel) send() error {
	if mp.Client == nil {
		mp.Client = http.DefaultClient
	}

	u, err := url.Parse("http://api.mixpanel.com/track/")
	if err != nil {
		return err
	}
	v := url.Values{}

	// Go -> JSON -> base64 -> ioutil.ReadAll()
	//
	// json.NewEncoder(buf)
	// base64.NewEncoder(base64.URLEncoding, buf)
	// ioutil.ReadAll(base64enc)

	if mp.Verbose {
		log.Printf("About to send data to mixpanel for event %q: %#v", mp.Event, mp.Properties)
	}

	buf := &bytes.Buffer{}
	baseEnc := base64.NewEncoder(base64.URLEncoding, buf)
	jsonEnc := json.NewEncoder(baseEnc)

	jsonEnc.Encode(mp)

	// Close baseEnc to flush partially written blocks:
	baseEnc.Close()

	v.Add("verbose", "1")
	v.Add("data", string(buf.Bytes()))
	u.RawQuery = v.Encode()

	resp, err := mp.Client.Get(u.String())
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return fmt.Errorf("Error reading mixpanel response: %v", err)
	}

	mpResp := &MixpanelResponse{}
	if err := json.Unmarshal(body, mpResp); err != nil {
		return fmt.Errorf("Error unmarshalling mixpanel response: %v", err)
	}

	if mpResp.Status == 0 {
		return fmt.Errorf("Got error from mixpanel: %v", mpResp.Error)
	}

	return nil
}
