package localserver

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"net/http"
)

type ChatNotificationsHandler struct {
	ChatId        string
	Initiator     string
	Target        string
	InitiatorHost string
	TargetHost    string
	DataChannels  map[string]*DataChannel
	Flag          *uint32
	//DB            *ChatNotificationDBHandler
	Publishers []<-chan *ChatRequest
	reqChans   []chan<- *ChatRequest
}

func NewChatNotificationsHandler(chatId, initiator, target, initiatorHost, targetHost string, dataChannels map[string]*DataChannel, flag *uint32) (chatNotificationsHandler *ChatNotificationsHandler, err error) {
	// if _, dirErr := os.ReadDir(filepath.Join(dataPath, "data", "zones", zoneId, "notifications")); os.IsNotExist(dirErr) {
	// 	dirErr := os.MkdirAll(filepath.Join(dataPath, "data", "zones", zoneId, "notifications"), 0700)
	// 	if dirErr != nil {
	// 		return
	// 	}
	// }
	chatNotificationsHandler = &ChatNotificationsHandler{
		ChatId:        chatId,
		Initiator:     initiator,
		Target:        target,
		InitiatorHost: initiatorHost,
		TargetHost:    targetHost,
		DataChannels:  dataChannels,
		Flag:          flag,
	}
	return
}

func (znh *ChatNotificationsHandler) Init(ctx context.Context, initiator, target, initiatorNodeID, targetNodeID string) (err error) {
	//? initialization code here
	return
}

func (znh *ChatNotificationsHandler) Subscribe(ctx context.Context, publisher <-chan *ChatRequest) (reqChan chan *ChatRequest, done chan struct{}, errCh chan error) {
	reqChan, done, errCh = make(chan *ChatRequest), 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.handleChatRequest(ctx, req); err != nil {
					errCh <- err
				}
			}
		}
	}()
	return
}

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

func (znh *ChatNotificationsHandler) 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 *ChatNotificationsHandler) DeleteNotification() {}

func (znh *ChatNotificationsHandler) PushNotification(notificationType, title, body, payload string, recipients ...string) (err error) {
	fmt.Println("*E*Z*E*Z*Z*E*Z**E*Z**E**Z*E****ZD*Z*")
	fmt.Println("this function has been called")
	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 = http.Post("https://dev.zippytal.com/req", "application/json", bytes.NewReader(b))
	if err != nil {
		fmt.Println("error inn notification sender", err)
		// logger.Println("error come from there in zone manager")
		return
	}
	return
}

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

func (znh *ChatNotificationsHandler) handleChatRequest(ctx context.Context, req *ChatRequest) (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
}
