package dao

import (
	"dhcp/global"
	"dhcp/model"
)

// 初始化数据库指针

var db = global.DB

func AddDHCP(dhcp model.DHCP) error {
	var dp model.DHCP
	tx := db.Model(&model.DHCP{}).Where("mac_address = ?", dhcp.MACAddress).First(dp)
	if tx.Error != nil {
		return tx.Error
	}
	if dp.Id == 0 {
		tx = db.Create(&dhcp)
	} else {
		tx = db.Model(&model.DHCP{}).Where("mac_address = ?", dhcp.MACAddress).Updates(dhcp)
	}

	if tx.Error != nil {
		return tx.Error
	}
	return nil
}

func GetDHCPByMac(macAddress string) (model.DHCP, error) {
	var dhcp model.DHCP
	tx := db.Model(&model.DHCP{}).Where("mac_address = ?", macAddress).First(&dhcp)
	if tx.Error != nil {
		return dhcp, tx.Error
	}
	return dhcp, nil
}

func GetDHCP() ([]model.DHCP, error) {
	var dhcp []model.DHCP
	tx := db.Model(&model.DHCP{}).Find(&dhcp)
	if tx.Error != nil {
		return nil, tx.Error
	}
	return dhcp, nil
}

func DeleteDHCP(macAddress string) error {
	tx := db.Model(&model.DHCP{}).Where("mac_address = ?", macAddress).Delete(&model.DHCP{})
	if tx.Error != nil {
		return tx.Error
	}
	return nil
}

func UpdateDHCP(dhcp model.DHCP) error {
	tx := db.Model(&model.DHCP{}).Where("mac_address = ?", dhcp.MACAddress).Updates(dhcp)
	if tx.Error != nil {
		return tx.Error
	}
	return nil
}
