package action

import (
	"crm-api/internal/app/ami"
	"crm-api/internal/app/ami/model"
	"encoding/json"
)

func PJSIPShowEndpoints() (points []*model.EndpointList, err error) {
	var action = map[string]string{
		"Action": "PJSIPShowEndpoints",
	}
	_, events, err := ami.AminInstance.Send(action)

	if err != nil {
		return nil, err
	}

	points = make([]*model.EndpointList, 0)
	for _, event := range events {
		if event.Data["Event"] == "EndpointList" {
			data, _ := json.Marshal(event.Data)
			point := &model.EndpointList{}
			json.Unmarshal(data, point)
			points = append(points, point)
		}
	}
	return points, nil
}

func PJSIPShowContacts() (points []*model.ContactList, err error) {
	points = make([]*model.ContactList, 0)
	var action = map[string]string{
		"Action": "PJSIPShowContacts",
	}
	_, events, err := ami.AminInstance.Send(action)

	if err != nil {
		return points, err
	}

	for _, event := range events {
		if event.Data["Event"] == "ContactList" {
			data, _ := json.Marshal(event.Data)
			point := &model.ContactList{}
			json.Unmarshal(data, point)
			points = append(points, point)
		}
	}
	return points, nil
}

func SIPPeers() (points []*model.PeerEntry, err error) {
	var action = map[string]string{
		"Action": "SIPPeers",
	}
	_, events, err := ami.AminInstance.Send(action)

	if err != nil {
		return nil, err
	}

	points = make([]*model.PeerEntry, 0)
	for _, event := range events {
		if event.Data["Event"] == "PeerEntry" {
			data, _ := json.Marshal(event.Data)
			point := &model.PeerEntry{}
			json.Unmarshal(data, point)
			points = append(points, point)
		}
	}
	return points, nil
}
