package apiv1

import (
	"time"

	"code.secondbit.org/ducky/devices.hg"
	"code.secondbit.org/uuid.hg"
)

// Device represents a device as exposed through the API. It is its
// own type as the business logic and the API have different requirements
// for the Device type, and require different representations.
type Device struct {
	ID        uuid.ID            `json:"id"`
	Name      string             `json:"name,omitempty"`
	Owner     uuid.ID            `json:"owner,omitempty"`
	Type      devices.DeviceType `json:"type,omitempty"`
	Created   time.Time          `json:"created,omitempty"`
	LastSeen  time.Time          `json:"lastSeen,omitempty"`
	PushToken string             `json:"pushToken,omitempty"`
}

// DeviceChange represents a set of changes to a device that will be used
// to update that device. It is its own type as the business logic and the
// API have different requirements for the DeviceChange type, and require
// different representations.
type DeviceChange struct {
	DeviceID  uuid.ID             `json:"id"`
	Name      *string             `json:"name,omitempty"`
	Owner     *uuid.ID            `json:"owner,omitempty"`
	Type      *devices.DeviceType `json:"type,omitempty"`
	LastSeen  *time.Time          `json:"lastSeen,omitempty"`
	PushToken *string             `json:"pushToken,omitempty"`
}

func apiDeviceFromCore(d devices.Device, includePushToken bool) Device {
	device := Device{
		ID:       d.ID,
		Name:     d.Name,
		Owner:    d.Owner,
		Type:     d.Type,
		Created:  d.Created,
		LastSeen: d.LastSeen,
	}
	if includePushToken {
		device.PushToken = d.PushToken
	}
	return device
}

func changeFromAPI(d DeviceChange) devices.DeviceChange {
	return devices.DeviceChange{
		DeviceID:  d.DeviceID,
		Name:      d.Name,
		Owner:     d.Owner,
		Type:      d.Type,
		LastSeen:  d.LastSeen,
		PushToken: d.PushToken,
	}
}

func createDevicesFromChanges(changes []DeviceChange) []devices.Device {
	newDevices := make([]devices.Device, 0, len(changes))
	for _, change := range changes {
		newDevices = append(newDevices, devices.ApplyChange(devices.Device{}, changeFromAPI(change)))
	}
	return newDevices
}

func validateDeviceCreation(d devices.Device) error {
	return nil
}
