/*

Copyright (c) 2016, the flickelectricnz Go package authors

Permission to use, copy, modify, and/or distribute this software for any purpose
with or without fee is hereby granted, provided that the above copyright notice
and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.

*/

package flickelectricnz

import (
	"encoding/json"
	"errors"
	"net/http"
	"net/url"
	"time"
)

const (
	oauth_endpoint string = "https://api.flick.energy/identity/oauth/token"
	price_endpoint string = "https://api.flick.energy/customer/mobile_provider/price"
	client_id      string = "le37iwi3qctbduh39fvnpevt1m2uuvz"
	client_secret  string = "ignwy9ztnst3azswww66y9vd9zt6qnt"
)

type Authorisation struct {
	token      string
	starttime  int64
	expiretime int64
}

type PriceInformation struct {
	NeedlePosition int     `json:"position"`
	PriceCents     float64 `json:"price"`
	Commentary     string  `json:"commentary"`
}

type flickOauthResponse struct {
	AccessToken string `json:"access_token"`
	ExpiresIn   int64  `json:"expires_in"`
	IDToken     string `json:"id_token"`
	TokenType   string `json:"token_type"`
}

type flickPriceResponse struct {
	Kind          string           `json:"kind"`
	CustomerState string           `json:"customer_state"`
	Needle        PriceInformation `json:"needle"`
}

// Login attempts to create an authorisation against the Flick service. The
// resulting Authorisation struct can be used to perform methods against the
// Flick service.
func Login(username, password string) (*Authorisation, error) {
	ret := Authorisation{
		starttime:  time.Now().Unix(),
		expiretime: 0,
	}

	resp, err := http.PostForm(
		oauth_endpoint,
		url.Values{
			"grant_type":    []string{"password"},
			"client_id":     []string{client_id},
			"client_secret": []string{client_secret},
			"username":      []string{username},
			"password":      []string{password},
		},
	)

	if err != nil {
		return nil, err
	}

	responseStruct := flickOauthResponse{}
	err = json.NewDecoder(resp.Body).Decode(&responseStruct)
	if err != nil {
		return nil, err
	}

	ret.token = responseStruct.IDToken
	ret.expiretime = ret.starttime + responseStruct.ExpiresIn

	return &ret, nil
}

// Valid checks whether the authorisation has not expired.
func (this *Authorisation) Valid() bool {
	now := time.Now().Unix()
	return now >= this.starttime && now < this.expiretime
}

// Retrieve the current price needle.
func (this *Authorisation) GetPrice() (*PriceInformation, error) {
	if !this.Valid() {
		return nil, errors.New("Expired authorisation")
	}

	req, err := http.NewRequest("GET", price_endpoint, nil)
	if err != nil {
		return nil, err
	}

	req.Header.Set("Authorization", "Bearer "+this.token)
	httpc := http.Client{}
	resp, err := httpc.Do(req)
	if err != nil {
		return nil, err
	}

	fpr := flickPriceResponse{}
	err = json.NewDecoder(resp.Body).Decode(&fpr)
	if err != nil {
		return nil, err
	}

	if fpr.Kind != "mobile_provider_price" {
		return nil, errors.New("Unexpected 'kind' value in response")
	}

	return &fpr.Needle, nil
}
