package models

import (
	"fmt"

	"github.com/pocketbase/pocketbase/core"
	"github.com/pocketbase/pocketbase/tools/security"
)

const (
	CameraFPassword     = "password"
	CameraFRecordStream = "record_stream"
)

type Camera struct {
	core.BaseRecordProxy
}

func (c *Camera) Name() string {
	return c.GetString("name")
}

func (c *Camera) OnvifHost() string {
	return c.GetString("onvif_host")
}

func (c *Camera) Username() string {
	return c.GetString("username")
}

func (c *Camera) PasswordRaw() string {
	return c.GetString(CameraFPassword)
}

func (c *Camera) Password(key string) (string, error) {
	password, err := security.Decrypt(c.PasswordRaw(), key)
	if err != nil {
		return "", fmt.Errorf("failed to decrypt password: %w", err)
	}
	return string(password), nil
}

func (c *Camera) SetPassword(password string, key string) error {
	encrypted, err := security.Encrypt([]byte(password), key)
	if err != nil {
		return fmt.Errorf("failed to encrypt password: %w", err)
	}
	c.Set(CameraFPassword, encrypted)
	return nil
}

func (c *Camera) RecordStreamID() string {
	return c.GetString(CameraFRecordStream)
}

func (c *Camera) RecordStream() *Stream {
	if r := c.ExpandedOne(CameraFRecordStream); r != nil {
		stream := &Stream{}
		stream.SetProxyRecord(r)
		return stream
	}
	return nil
}
