package backend

import (
	"github.com/glebarez/sqlite"
	"gorm.io/gorm"
	"os"
	"path/filepath"
)

type Dhcp struct {
	Id               int      `json:"id" gorm:"id"`                               // ID
	MACAddress       string   `json:"mac_address" gorm:"mac_address"`             // MAC地址
	IPAddress        string   `json:"ip_address" gorm:"ip_address"`               // IP地址
	SubnetMask       string   `json:"subnet_mask" gorm:"subnet_mask"`             // 子网掩码
	DefaultGateway   string   `json:"default_gateway" gorm:"default_gateway"`     // 默认网关
	NameServers      []string `json:"name_servers" gorm:"name_servers"`           // DNS服务器
	DomainName       string   `json:"domain_name" gorm:"domain_name"`             // 域名
	BroadcastAddress string   `json:"broadcast_address" gorm:"broadcast_address"` // 广播地址
	NTPServers       []string `json:"ntp_servers" gorm:"ntp_servers"`             // NTP服务器
	VLANID           string   `json:"vlan_id" gorm:"vlan_id"`                     // VLAN ID
	LeaseTime        uint32   `json:"lease_time" gorm:"lease_time"`               // 租约
	DomainSearch     []string `json:"domain_search" gorm:"domain_search"`         // 域名搜索
	ServerIP         string   `json:"server_ip" gorm:"server_ip"`                 // 服务器IP
}

// 定义数据库指针
var db *gorm.DB

// 初始化数据库指针
func InitDB() {
	executablePath, err := os.Executable()
	if err != nil {
		panic(err)
	}
	dbPath := filepath.Join(filepath.Dir(executablePath), "dhcp.db")
	db, err = gorm.Open(sqlite.Open(dbPath), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	db.AutoMigrate(&Dhcp{})
}

func AddDhcp(dhcp Dhcp) error {
	var dp Dhcp
	tx := db.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(&Dhcp{}).Where("mac_address = ?", dhcp.MACAddress).Updates(dhcp)
	}

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

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

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

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