package sharedmodel

import (
	"database/sql/driver"
	"encoding/json"
	"errors"
	"fmt"

	"src.whiteboxsystems.nl/DECOZO/okapi"
)

type Protocol struct {
	Protocol    string
	AuthMethods []string
}

type ListOfStrings []string

// Scan scan value into Jsonb, implements sql.Scanner interface
func (j *ListOfStrings) Scan(value interface{}) error {
	bytes, ok := value.([]byte)
	if !ok {
		return errors.New(fmt.Sprint("Failed to unmarshal ListOfStrings value:", value))
	}

	result := []string{}
	err := json.Unmarshal(bytes, &result)
	*j = ListOfStrings(result)
	return err
}

// Value return json value, implement driver.Valuer interface
func (j ListOfStrings) Value() (driver.Value, error) {
	if len(j) == 0 {
		return nil, nil
	}
	return json.Marshal(j)
}

type ProtocolArray []Protocol

// Scan scan value into Jsonb, implements sql.Scanner interface
func (j *ProtocolArray) Scan(value interface{}) error {
	bytes, ok := value.([]byte)
	if !ok {
		return errors.New(fmt.Sprint("Failed to unmarshal ProtocolArray value:", value))
	}

	result := []Protocol{}
	err := json.Unmarshal(bytes, &result)
	*j = ProtocolArray(result)
	return err
}

// Value return json value, implement driver.Valuer interface
func (j ProtocolArray) Value() (driver.Value, error) {
	if len(j) == 0 {
		return nil, nil
	}
	return json.Marshal(j)
}

type AuthMethodArray []okapi.ProtocolAuthConfiguration

// Scan scan value into Jsonb, implements sql.Scanner interface
func (j *AuthMethodArray) Scan(value interface{}) error {
	bytes, ok := value.([]byte)
	if !ok {
		return errors.New(fmt.Sprint("Failed to unmarshal AuthMethodArray value:", value))
	}

	result := []okapi.ProtocolAuthConfiguration{}
	err := json.Unmarshal(bytes, &result)
	*j = AuthMethodArray(result)
	return err
}

// Value return json value, implement driver.Valuer interface
func (j AuthMethodArray) Value() (driver.Value, error) {
	if len(j) == 0 {
		return nil, nil
	}
	return json.Marshal(j)
}
