package starnotify

import (
	"errors"
	"time"

	"b612.me/notify/v1"
)

var (
	starClient map[string]*notify.StarNotifyC
	starServer map[string]*notify.StarNotifyS
)

func init() {
	starClient = make(map[string]*notify.StarNotifyC)
	starServer = make(map[string]*notify.StarNotifyS)
}

func NewClient(key, netype, value string) (*notify.StarNotifyC, error) {
	client, err := notify.NewNotifyC(netype, value)
	if err != nil {
		return client, err
	}
	starClient[key] = client
	return client, err
}

func NewClientWithTimeout(key, netype, value string, timeout time.Duration) (*notify.StarNotifyC, error) {
	client, err := notify.NewNotifyCWithTimeOut(netype, value, timeout)
	if err != nil {
		return client, err
	}
	starClient[key] = client
	return client, err
}

func DeleteClient(key string) error {
	client, ok := starClient[key]
	if !ok {
		return errors.New("Not Exists Yet!")
	}
	if client.Online {
		client.ClientStop()
	}
	client = nil
	delete(starClient, key)
	return nil
}

func NewServer(key, netype, value string) (*notify.StarNotifyS, error) {
	server, err := notify.NewNotifyS(netype, value)
	if err != nil {
		return server, err
	}
	starServer[key] = server
	return server, err
}

func DeleteServer(key string) error {
	server, ok := starServer[key]
	if !ok {
		return errors.New("Not Exists Yet!")
	}
	if server.Online {
		server.ServerStop()
	}
	server = nil
	delete(starServer, key)
	return nil
}

func S(key string) *notify.StarNotifyS {
	server, ok := starServer[key]
	if !ok {
		return nil
	}
	return server
}

func C(key string) *notify.StarNotifyC {
	client, ok := starClient[key]
	if !ok {
		return nil
	}
	return client
}

func Server(key string) (*notify.StarNotifyS, error) {
	server, ok := starServer[key]
	if !ok {
		return nil, errors.New("Not Exists Yet")
	}
	return server, nil
}

func Client(key string) (*notify.StarNotifyC, error) {
	client, ok := starClient[key]
	if !ok {
		return nil, errors.New("Not Exists Yet")
	}
	return client, nil
}