package queries

import (
	"github.com/fiskerinc/cloud-services/pkg/common"

	"github.com/go-pg/pg/v10/orm"
	"github.com/google/uuid"
	"github.com/pkg/errors"
)

var subConfigurationCols = []string{}

type SubscriptionConfigurationsInterface interface {
	Delete(model *common.SubscriptionConfiguration) (orm.Result, error)
	Insert(model *common.SubscriptionConfiguration) (orm.Result, error)
	Update(model *common.SubscriptionConfiguration) (orm.Result, error)
	Count(filter *common.SubscriptionConfiguration) (int, error)
	Select(fitler *common.SubscriptionConfiguration, paging *PageQueryOptions) ([]common.SubscriptionConfiguration, error)
}

type SubscriptionConfigurations struct {
	QueryBase
}

func (sc *SubscriptionConfigurations) Delete(model *common.SubscriptionConfiguration) (orm.Result, error) {
	return sc.delete(model)
}

func (sc *SubscriptionConfigurations) Insert(model *common.SubscriptionConfiguration) (orm.Result, error) {
	return sc.insert(model)
}

func (sc *SubscriptionConfigurations) Update(model *common.SubscriptionConfiguration) (orm.Result, error) {
	return sc.resultWithStack(sc.GetDBConn().Model(model).Column(subConfigurationCols...).WherePK().Update())
}

func (sc *SubscriptionConfigurations) Count(filter *common.SubscriptionConfiguration) (int, error) {
	query := sc.GetDBConn().Model(filter)

	sc.selectFilter(query, filter)

	count, err := query.Count()

	return count, errors.WithStack(err)
}

func (sc *SubscriptionConfigurations) selectFilter(query *orm.Query, filter *common.SubscriptionConfiguration) {
	if filter.SubscriptionFeatureID != uuid.Nil {
		query.Where("subscription_feature_id = ?", filter.SubscriptionFeatureID)
	}

	if filter.ECU != "" {
		query.Where("ecu = ?", filter.ECU)
	}

	if filter.HardwareVersion != "" {
		query.Where("hardware_version = ?", filter.HardwareVersion)
	}

	if filter.SoftwareVersion != "" {
		query.Where("software_version = ?", filter.SoftwareVersion)
	}

	if filter.DID != nil {
		query.Where("did = decode(?, 'hex')", filter.DID.String())
	}

	if filter.PID != nil {
		query.Where("pid = decode(?, 'hex')", filter.PID.String())
	}

	if filter.Configuration != nil {
		query.Where("configuration = decode(?, 'hex')", filter.Configuration.String())
	}

	if filter.Mask != nil {
		query.Where("mask = decode(?, 'hex')", filter.Mask.String())
	}
}

func (sc *SubscriptionConfigurations) Select(filter *common.SubscriptionConfiguration, paging *PageQueryOptions) ([]common.SubscriptionConfiguration, error) {
	items := []common.SubscriptionConfiguration{}
	query := sc.GetDBConn().Model(&items)

	sc.selectFilter(query, filter)
	if paging != nil {
		sc.pageQuery(query, paging)
	}

	err := query.Select()

	return items, errors.WithStack(err)
}
