// MIT License
//
// Copyright (c) 2020 Alex Howarth
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

package tilt

import (
	"encoding/hex"
	"log"
	"math"

	"github.com/pkg/errors"
)

// tiltIdentifier iBeacon identifier portion (4c000215) as well as Tilt specific uuid preamble (a495)
const tiltIdentifier = "4c000215a495"

// ErrNotTilt - the BLE device does not match anything in tiltType
var ErrNotTilt = errors.New("Not a Tilt iBeacon")

// Color of the Tilt
type Color string

var tiltType = map[string]Color{
	"a495bb10c5b14b44b5121370f02d74de": "Red",
	"a495bb20c5b14b44b5121370f02d74de": "Green",
	"a495bb30c5b14b44b5121370f02d74de": "Black",
	"a495bb40c5b14b44b5121370f02d74de": "Purple",
	"a495bb50c5b14b44b5121370f02d74de": "Orange",
	"a495bb60c5b14b44b5121370f02d74de": "Blue",
	"a495bb70c5b14b44b5121370f02d74de": "Yellow",
	"a495bb80c5b14b44b5121370f02d74de": "Pink",
}

// Tilt struct
type Tilt struct {
	col  Color
	temp uint16
	sg   uint16
}

// NewTilt returns a Tilt from an iBeacon
func NewTilt(b *IBeacon) (t Tilt, err error) {
	if col, ok := tiltType[b.UUID]; ok {
		t = Tilt{col: col, temp: b.Major, sg: b.Minor}
		return
	}
	err = ErrNotTilt
	return
}

// IsTilt tests if the data is from a Tilt
func IsTilt(d []byte) bool {
	if len(d) >= 25 && hex.EncodeToString(d)[0:12] == tiltIdentifier {
		return true
	}
	return false
}

func (t *Tilt) Celsius() float64 {
	return math.Round(float64(t.temp-32)/1.8*100) / 100
}

func (t *Tilt) Fahrenheit() uint16 {
	return t.temp
}

func (t *Tilt) Gravity() float64 {
	return float64(t.sg) / 1000
}

func (t *Tilt) Color() Color {
	return t.col
}

func (t *Tilt) Print() {
	log.Printf("Tilt: color=%v specific_gravity=%v temp_celcius=%v", t.Color(), t.Gravity(), t.Celsius())
}
