package service

import (
	"sws_xcx/models"

	"github.com/jinzhu/gorm"
)

type XcxUserService struct {
	rdb *gorm.DB
	wdb *gorm.DB
}

func NewXcxUserService() *XcxUserService {
	u := &models.XcxUser{}
	return &XcxUserService{rdb: readDb.Model(u), wdb: writeDb.Model(u)}
}

func (s *XcxUserService) GetUser(id uint64) (*models.XcxUser, error) {

	user := &models.XcxUser{}
	db := readDb.Where("id=?", id).First(user)

	return user, db.Error

}

func (s *XcxUserService) GetOrCreate(openId string, unionId string) (*models.XcxUser, error) {

	user := &models.XcxUser{OpenId: openId, UnionId: unionId}
	db := writeDb.Where("open_id = ?", openId).Or("union_id = ?", unionId).FirstOrCreate(user)

	return user, db.Error

}

func (s *XcxUserService) UpdateUser(user *models.XcxUser) error {

	db := writeDb.Where("id = ?", user.Id).Update(user)

	return db.Error

}
