package localserver

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
)

type SquadNotificationsHandler struct {
	SquadId        string
	SquadMembersId []string
	DataChannels   map[string]*DataChannel
	Flag           *uint32
	Publishers     []<-chan *SquadRequest
	reqChans       []chan<- *SquadRequest
}

func NewSquadNotificationsHandler(_ string, squadId string, owner string, authorizedMembers []string, dataChannels map[string]*DataChannel, flag *uint32) (squadNotificationsHandler *SquadNotificationsHandler, err error) {
	if _, dirErr := os.ReadDir(filepath.Join(dataPath, "data", "squads", squadId, "notifications")); os.IsNotExist(dirErr) {
		dirErr := os.MkdirAll(filepath.Join(dataPath, "data", "squads", squadId, "notifications"), 0700)
		if dirErr != nil {
			return
		}
	}
	squadNotificationsHandler = &SquadNotificationsHandler{
		SquadId:        squadId,
		SquadMembersId: authorizedMembers,
		DataChannels:   dataChannels,
		Flag:           flag,
	}
	return
}

func (znh *SquadNotificationsHandler) Init(ctx context.Context, authorizedMembers []string) (err error) {
	//? initialization code here
	return
}

func (znh *SquadNotificationsHandler) Subscribe(ctx context.Context, publisher <-chan *SquadRequest) (reqChan chan *SquadRequest, done chan struct{}, errCh chan error) {
	reqChan, done, errCh = make(chan *SquadRequest), make(chan struct{}), make(chan error)
	znh.reqChans = append(znh.reqChans, reqChan)
	go func() {
		for {
			select {
			case <-ctx.Done():
				done <- struct{}{}
				return
			case req := <-publisher:
				if err := znh.handleSquadRequest(ctx, req); err != nil {
					errCh <- err
				}
			}
		}
	}()
	return
}

func (znh *SquadNotificationsHandler) ListNotifications(userId string) {}

func (znh *SquadNotificationsHandler) CreateNotification(notificationType, title, body, payload string, isPushed bool, recipients ...string) (err error) {
	if isPushed {
		err = znh.PushNotification(notificationType, title, body, payload, recipients...)
	}
	return
}

func (znh *SquadNotificationsHandler) DeleteNotification() {}

func (znh *SquadNotificationsHandler) PushNotification(notificationType, title, body, payload string, recipients ...string) (err error) {
	em := NewEncryptionManager()
	sig := em.SignRequestHMAC(NodeID)
	b, err := json.Marshal(map[string]interface{}{
		"type":     NOTIFY,
		"mac":      sig,
		"from":     NodeID,
		"peerType": "node",
		"payload": map[string]interface{}{
			"type":       notificationType,
			"title":      title,
			"body":       body,
			"recipients": recipients,
			"payload":    payload,
		},
	})
	if err != nil {
		return
	}
	_, err = HTTPClient.Post("https://dev.zippytal.com/req", "application/json", bytes.NewReader(b))
	if err != nil {
		// logger.Println("error come from there in squad manager")
		return
	}
	return
}

func (znh SquadNotificationsHandler) handleDataChannel(ctx context.Context, dc *DataChannel) (catched bool) {
	return
}

func (znh *SquadNotificationsHandler) handleSquadRequest(ctx context.Context, req *SquadRequest) (err error) {
	switch req.ReqType {
	case CREATE_NOTIFICATION:
		if err = VerifyFieldsString(req.Payload, "type", "title", "body", "payload"); err != nil {
			return
		}
		if err = VerifyFieldsBool(req.Payload, "isPushed"); err != nil {
			return
		}
		if _, ok := req.Payload["recipients"]; !ok {
			err = fmt.Errorf("no field recipient in payload")
			return
		}
		if _, ok := req.Payload["recipients"].([]string); !ok {
			err = fmt.Errorf(" field recipient in payload is wrong type")
			return
		}

		err = znh.CreateNotification(req.Payload["type"].(string), req.Payload["title"].(string), req.Payload["body"].(string), req.Payload["payload"].(string), req.Payload["isPushed"].(bool), req.Payload["recipients"].([]string)...)
	}
	return
}
