package service

import (
	"sws_xcx/models"

	"github.com/jinzhu/gorm"
)

type CheckItemService struct {
	rdb *gorm.DB
}

func NewCheckItemService() *CheckItemService {
	return &CheckItemService{
		rdb: ReadDB().Model(&models.CheckItem{}),
	}
}

func (s *CheckItemService) GetCheckItems(lang, t string) ([]*models.CheckItem, error) {
	var items []*models.CheckItem
	db := s.rdb.Where(" delete_flag = ?", 0)
	if t != "" {
		db = db.Where("device_type = ?", t)
	}
	if lang != "" {
		db = db.Where("language = ? ", lang)
	}
	err := db.Order("check_item_number").Find(&items).Error
	return items, err
}

func (s *CheckItemService) GetCheckItemById(id int64) (item models.CheckItem, err error) {
	err = s.rdb.Where("id = ?", id).First(&item).Error
	if err == gorm.ErrRecordNotFound {
		err = nil
	}
	return
}

func (s *CheckItemService) GetCheckItemByNumber(number int, lang, deviceType string) (item models.CheckItem, err error) {
	err = s.rdb.Where("check_item_number = ? and language= ? and device_type= ? ", number, lang, deviceType).First(&item).Error
	if err == gorm.ErrRecordNotFound {
		err = nil
	}
	return
}
