package models

import (
	"bwallet/pkg/setting"
	"github.com/jinzhu/gorm"
)

type LiveCharge struct {
	Model

	Unit       string  `json:"unit"`
	PlatformId int64   `json:"platform_id"`
	UnitPrice  float64 `json:"unit_price"`
}

func (w LiveCharge) TableName() string {
	return setting.DatabaseSetting.Name_Sources + ".wallet_live_charge"
}

func GetOneLiveCharge(id int) (*LiveCharge, error) {
	var charge LiveCharge
	err := db.Where("id = ?", id).First(&charge).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	err = db.Model(&charge).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	return &charge, nil
}

func ExistLiveChargeById(id int) (bool, error) {
	var charge LiveCharge
	err := db.Select("id").Where("id = ?", id).First(&charge).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return false, err
	}

	if charge.ID > 0 {
		return true, nil
	}

	return false, nil
}

func GetLiveChargeTotal(maps interface{}) (int, error) {
	var count int

	if err := db.Model(&LiveCharge{}).Where(maps).Count(&count).Error; err != nil {
		return 0, err
	}

	return count, nil
}

func GetLiveCharge(pageNum, pageSize int, maps interface{}) ([]*LiveCharge, error) {
	var charge []*LiveCharge

	err := db.Where(maps).Order("id desc").Offset(pageNum).Limit(pageSize).Find(&charge).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	return charge, nil
}

func AddLiveCharge(data map[string]interface{}) (error) {
	charge := LiveCharge{
		Unit:       data["unit"].(string),
		PlatformId: data["platform_id"].(int64),
		UnitPrice:  data["unit_price"].(float64),
	}

	if err := db.Create(&charge).Error; err != nil {
		return err
	}

	return nil
}

func EditLiveCharge(id int, data interface{}) error {
	if err := db.Model(&LiveCharge{}).Where("id = ?", id).Updates(data).Error; err != nil {
		return err
	}

	return nil
}
