package service

import (
	"context"
	"dsbqj-admin/app/task"
	"dsbqj-admin/model/mongo/version"
	"github.com/kamva/mgm/v3"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
)

type VersionReloadService struct {
}

func (service *VersionReloadService) Reload() error {
	task.VersionTask.Exec()
	return nil
}

type VersionServerService struct {
}

func (service *VersionServerService) Servers() ([]*version.Version, error) {
	return task.VersionTask.Servers(), nil
}

type VersionCheckService struct {
	Version string `json:"version" binding:"required"`
}

func (service *VersionCheckService) Check() (*version.Version, error) {
	return task.VersionTask.Check(service.Version), nil
}

type VersionShowService struct {
	CondPage
}

func (service *VersionShowService) List() ([]version.Version, error) {
	versions := make([]version.Version, 0)
	err := mgm.Coll(&version.Version{}).SimpleFind(&versions, bson.M{})
	return versions, err
}

type VersionCreateService struct {
	Version string `json:"version" binding:"required"`
	Name    string `json:"name" binding:"required"`
	CDN     string `json:"cdn" binding:"required"`
	Url     string `json:"url" binding:"required"`
}

func (service *VersionCreateService) Create() error {
	version := new(version.Version)
	version.Name = service.Name
	version.Version = service.Version
	version.CDN = service.CDN
	version.Url = service.Url

	return mgm.Coll(version).Create(version)
}

type VersionEditService struct {
	Id      string  `json:"id" binding:"required"`
	Version *string `json:"version"`
	Name    *string `json:"name"`
	CDN     *string `json:"cdn"`
	Url     *string `json:"url"`
	Default *bool   `json:"default"`
}

func (service *VersionEditService) Edit() error {
	version := new(version.Version)

	objectId, _ := primitive.ObjectIDFromHex(service.Id)
	filterDoc := bson.M{"_id": objectId}
	updateDoc := bson.M{}
	if service.Name != nil {
		updateDoc["name"] = service.Name
	}
	if service.Version != nil {
		updateDoc["version"] = service.Version
	}
	if service.CDN != nil {
		updateDoc["cdn"] = service.CDN
	}
	if service.Url != nil {
		updateDoc["url"] = service.Url
	}
	if service.Default != nil {
		updateDoc["default"] = service.Default
	}

	_, err := mgm.Coll(version).UpdateOne(context.Background(), filterDoc, bson.M{"$set": updateDoc})

	return err
}

type VersionDeleteService struct {
	Id string `json:"id" binding:"required"`
}

func (service *VersionDeleteService) Delete() error {
	version := new(version.Version)
	objectId, _ := primitive.ObjectIDFromHex(service.Id)
	filterDoc := bson.M{"_id": objectId}

	_, err := mgm.Coll(version).DeleteOne(context.Background(), filterDoc)
	return err
}
