package queries

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

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

type ECUInterface interface {
	Insert(dtc *[]common.DTC_ECU) (orm.Result, error)
	UpdateTimestamp(dtc *common.DTC_ECU) error
	Select(dtcecu common.DTC_ECUQuery, paging *PageQueryOptions) ([]common.DTC_ECU, error)
	Count(filter common.DTC_ECUQuery) (int, error)
}

type ECU struct {
	QueryBase
}

func (c *ECU) Insert(ecuDtc *[]common.DTC_ECU) (orm.Result, error) {
	if len(*ecuDtc) > 0 {
		return c.insert(ecuDtc)
	}
	return nil, nil
}

func (c *ECU) UpdateTimestamp(dtc *common.DTC_ECU) error {
	_, err := c.GetDBConn().Model(dtc).
		Where("vin = ?vin AND ecu = ?ecu AND trouble_code = ?trouble_code").
		Set("updated_at = ?", time.Now()).
		Update()
	return errors.WithStack(err)
}

func (c *ECU) Select(filter common.DTC_ECUQuery, paging *PageQueryOptions) ([]common.DTC_ECU, error) {

	dtcEcu := []common.DTC_ECU{}
	query := c.GetDBConn().Model(&dtcEcu)

	c.applyFilters(query, filter)
	c.pageQuery(query, paging)
	err := query.Select()
	if err != nil {
		return nil, errors.WithStack(err)
	}

	return dtcEcu, nil
}

func (c *ECU) applyFilters(query *orm.Query, filter common.DTC_ECUQuery) {

	query.Where("vin = ?", filter.VIN)

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

	if filter.TroubleCode != 0 {
		query.Where("trouble_code = ?", filter.TroubleCode)
	}

	if filter.StartTime != nil {
		query.Where("epoch_usec >= ?", filter.StartTime.Unix()*1000000)
	}

	if filter.EndTime != nil {
		query.Where("epoch_usec <= ?", filter.EndTime.Unix()*1000000)
	}
}

func (c *ECU) Count(filter common.DTC_ECUQuery) (int, error) {
	ecu_dtc := common.DTC_ECU{}
	query := c.GetDBConn().Model(&ecu_dtc)
	c.applyFilters(query, filter)
	return c.countWithStack(query.Count())
}
