/*
 * Copyright (c) 2024  The AdvantEDGE Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package sssmgr

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"reflect"
	"strconv"
	"strings"
	"sync"
	"time"

	log "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-logger"

	uuid "github.com/google/uuid"
	"github.com/gorilla/mux"
)

// Sensors-Sharing Service Manager
type SssMgr struct {
	name                 string
	namespace            string
	mutex                sync.Mutex
	wg                   sync.WaitGroup
	refreshTicker        *time.Ticker
	sss_discovery_notify func()
	sss_status_notify    func()
	sss_data_notify      func()
}

type IotPlatformInfo struct {
	Address       string
	Port          int
	Name          string
	IotPlatformId string
}

type Point struct {
	Latitude  float64
	Longitude float64
}

type SensorCharacteristic struct {
	CharacteristicName          string
	CharacteristicValue         string
	CharacteristicUnitOfMeasure *string
}

type SensorDiscoveryInfo struct {
	SensorIdentifier         string
	SensorType               string
	SensorPropertyList       []string
	SensorCharacteristicList []SensorCharacteristic
	SensorPosition           *Point
	IotPlatformId            string
}

var registeredIotPlatformsMap = map[string]IotPlatformInfo{} // List of discovered IOT Plateform
var sensorsMap = map[string]SensorDiscoveryInfo{}            // Map sensors by sensorIdentifier
var sensorsPerPlatformMap = map[string][]string{}            // Map dsensorIdentifiers per platform

// Timer to refresh devices list for all IoT platform
const refreshTickerExpeary = 10 // In seconds

// Enable profiling
const profiling = false

var profilingTimers map[string]time.Time

const (
	headerAccept         = "application/json"
	headerContentType    = "application/json"
	iot_platform_address = "lab-oai.etsi.org"
	iot_platform_port    = 31110
	iot_platform_name    = "laboai-acme-ic-cse"
	iot_platform_id      = "7feaadbb0400"
)

// NewSssMgr - Creates and initializes a new SSS Traffic Manager
func NewSssMgr(name string, namespace string, sss_discovery_notify func(), sss_status_notify func(), sss_data_notify func()) (tm *SssMgr, err error) {
	if name == "" {
		err = errors.New("Missing connector name")
		return nil, err
	}

	// Create new Traffic Manager
	tm = new(SssMgr)
	tm.name = name
	if namespace != "" {
		tm.namespace = namespace
	} else {
		tm.namespace = "default"
	}

	tm.sss_discovery_notify = sss_discovery_notify
	tm.sss_status_notify = sss_status_notify
	tm.sss_data_notify = sss_data_notify

	tm.init()

	return tm, nil
}

// Profiling init
func (tm *SssMgr) init() {
	if profiling {
		profilingTimers = make(map[string]time.Time)
	}

	registeredIotPlatformsMap = make(map[string]IotPlatformInfo, 1)
	registeredIotPlatformsMap[iot_platform_address] = IotPlatformInfo{ // FIXME FSCOM How to register IoT platform to meep-sss (see meep-iot?)
		Address:       iot_platform_address,
		Port:          iot_platform_port,
		Name:          iot_platform_name,
		IotPlatformId: iot_platform_id,
	}
	sensorsMap = make(map[string]SensorDiscoveryInfo, 0)
	sensorsPerPlatformMap = make(map[string][]string, 0)
	tm.refreshTicker = nil
}

// DeleteSssMgr -
func (tm *SssMgr) DeleteSssMgr() (err error) {
	tm.stopRefreshTicker()

	return nil
}

func (tm *SssMgr) startRefreshTicker() {
	log.Debug("Starting refresh loop")
	tm.refreshTicker = time.NewTicker(refreshTickerExpeary * time.Second)
	go func() {
		if tm.refreshTicker != nil {
			for range tm.refreshTicker.C {
				// Refresh the list of devices
				tm.wg.Add(1)
				err := tm.populateDevicesPerIotPlatforms()
				if err != nil {
					log.Error(err)
				}
				tm.wg.Done()
			}
		}
	}()
}

func (tm *SssMgr) stopRefreshTicker() {
	if tm.refreshTicker != nil {
		// Refresh the list of devices
		tm.wg.Add(1)
		tm.refreshTicker.Stop()
		tm.refreshTicker = nil
		registeredIotPlatformsMap = nil
		sensorsMap = nil
		sensorsPerPlatformMap = nil
		tm.wg.Done()
		log.Debug("Refresh loop stopped")
	}
}

func (tm *SssMgr) SensorDiscoveryInfoAll() (sensors []SensorDiscoveryInfo, err error) {
	if profiling {
		profilingTimers["GetDevices"] = time.Now()
	}

	log.Info(">>> SensorDiscoveryInfoAll")

	err = tm.populateDevicesPerIotPlatforms() // FIXME FSCOM User timer. See startRefreshTicker
	if err != nil {
		return sensors, err
	}

	tm.wg.Wait()
	log.Info("SensorDiscoveryInfoAll: After Synchro")

	sensors = make([]SensorDiscoveryInfo, 0)
	if len(registeredIotPlatformsMap) == 0 {
		return sensors, nil
	}

	for _, v := range sensorsMap {
		log.Info("SensorDiscoveryInfoAll: adding sensor: ", v)
		sensors = append(sensors, v)
	} // End of 'for' statement
	log.Info("SensorDiscoveryInfoAll: sensors: ", sensors)

	if profiling {
		now := time.Now()
		log.Debug("SensorDiscoveryInfoAll: ", now.Sub(profilingTimers["GetDevices"]))
	}

	return sensors, nil
}

func (tm *SssMgr) GetSensor(sensorIdentifier string) (sensor SensorDiscoveryInfo, err error) {
	if profiling {
		profilingTimers["GetSensor"] = time.Now()
	}

	log.Info(">>> GetSensor: sensorIdentifier: ", sensorIdentifier)

	tm.wg.Wait()
	log.Info("GetSensor: After Synchro")

	if val, ok := sensorsMap[sensorIdentifier]; !ok {
		err = errors.New("Wrong Device identifier")
		return sensor, err
	} else {
		sensor = val
	}

	if profiling {
		now := time.Now()
		log.Debug("GetSensor: ", now.Sub(profilingTimers["GetSensor"]))
	}
	log.Info("GetSensor: sensor: ", sensor)

	return sensor, nil
}

/*
 * func populateDevicesPerIotPlatforms IoT devices for all registered Iot platform
 * @return {struct} nil on success, error otherwise
 */
func (tm *SssMgr) populateDevicesPerIotPlatforms() error {

	tm.mutex.Lock()
	defer tm.mutex.Unlock()

	if profiling {
		profilingTimers["populateDevicesPerIotPlatforms"] = time.Now()
	}

	if len(registeredIotPlatformsMap) == 0 {
		return nil
	}

	// Refresh the list of devices for all registered Iot platform
	for _, iotPlatform := range registeredIotPlatformsMap {
		log.Debug("populateDevicesPerIotPlatforms: processing: ", iotPlatform.Address)
		err := tm.populateSensors(iotPlatform)
		if err != nil {
			log.Error("populateDevicesPerIotPlatforms: ", err)
			continue
		}
	} // End of 'for' statement

	if profiling {
		now := time.Now()
		log.Debug("populateDevicesPerIotPlatforms: ", now.Sub(profilingTimers["populateDevicesPerIotPlatforms"]))
	}

	return nil
}

/*
 * func PopulateDevices IoT devices for the specified Iot platform
 * @param {string} iotPlatformId contains the IoT platform identifier
 * @return {struct} nil on success, error otherwise
 */
func (tm *SssMgr) populateSensors(iotPlatformInfo IotPlatformInfo) error {
	if profiling {
		profilingTimers["populateSensors"] = time.Now()
	}

	log.Info(">>> populateSensors: iotPlatformId=", iotPlatformInfo.Address)

	// 1. Get the list of the AE
	// Build the URL
	url := "http://" + iotPlatformInfo.Address + ":" + strconv.Itoa(int(iotPlatformInfo.Port)) + "/" + iotPlatformInfo.Name
	log.Debug("populateSensors: url=", url)
	// Build the headers
	var headers = http.Header{}
	headers["Accept"] = []string{headerAccept}
	headers["Content-Type"] = []string{headerContentType}
	headers["X-M2M-Origin"] = []string{"CAdmin"} // FIXME FSCOM How to get it
	headers["X-M2M-RI"] = []string{uuid.New().String()}
	headers["X-M2M-RVI"] = []string{"4"} // FIXME FSCOM How to get it
	// Build the queries
	queries := map[string]string{}
	queries["fu"] = "1" // Filter usage
	queries["ty"] = "4" // Filter on oneM2M CIN for sensors
	// Send the request
	response, err := sendRequest("GET", url, headers, nil, nil, queries, 200)
	if err != nil {
		log.Error("populateSensors: ", err.Error())
		return err
	}
	log.Debug("populateSensors: response: ", string(response))

	var oneM2M_uril map[string][]string
	err = json.Unmarshal(response, &oneM2M_uril)
	if err != nil {
		log.Error("populateSensors: ", err.Error())
		return err
	}
	log.Debug("populateSensors: oneM2M_uril: ", len(oneM2M_uril))
	log.Debug(oneM2M_uril)
	if _, ok := oneM2M_uril["m2m:uril"]; !ok {
		err := errors.New("populateSensors: CharacteristicName not found: m2m:uril")
		log.Error(err.Error())
		return err
	}
	// Loop for each CIN and build the sensor list
	for _, v := range oneM2M_uril["m2m:uril"] {
		log.Debug("populateSensors: Processing key: ", v)

		url := "http://" + iotPlatformInfo.Address + ":" + strconv.Itoa(int(iotPlatformInfo.Port)) + "/" + v
		log.Debug("populateSensors: url=", url)
		// Build the headers
		var headers = http.Header{}
		headers["Accept"] = []string{headerAccept}
		headers["Content-Type"] = []string{headerContentType}
		headers["X-M2M-Origin"] = []string{"CAdmin"} // FIXME FSCOM How to get it
		headers["X-M2M-RI"] = []string{uuid.New().String()}
		headers["X-M2M-RVI"] = []string{"4"} // FIXME FSCOM How to get it
		// Build the queries
		queries := map[string]string{}
		queries["fu"] = "2" // Filter usage
		// Send the request
		response, err := sendRequest("GET", url, headers, nil, nil, queries, 200)
		if err != nil {
			log.Error("populateSensors: ", err.Error())
			return err
		}
		log.Debug("populateSensors: response: ", string(response))
		var oneM2M_cin map[string]map[string]interface{}
		err = json.Unmarshal(response, &oneM2M_cin)
		if err != nil {
			log.Error("populateSensors: ", err.Error())
			continue
		}
		log.Debug("populateSensors: type(oneM2M_cin): ", reflect.TypeOf(oneM2M_cin))
		log.Debug("populateSensors: len(oneM2M_cin): ", len(oneM2M_cin))
		log.Debug("populateSensors: oneM2M_cin: ", oneM2M_cin)
		for _, m := range oneM2M_cin {
			//log.Debug("==> ", i, " value is ", m)
			var sensor = SensorDiscoveryInfo{
				IotPlatformId: iotPlatformInfo.IotPlatformId,
			}

			// m is a map[string]interface.
			// loop over keys and values in the map.
			for k, v := range m {
				log.Debug(k, " value is ", v)
				log.Debug("populateSensors: type(v): ", reflect.TypeOf(v))

				if k == "ri" {
					if item, ok := v.(string); ok {
						sensor.SensorIdentifier = item
					} else {
						log.Error("populateSensors: Failed to process ", k)
					}
				} else if k == "ty" {
					if item, ok := v.(float64); ok {
						sensor.SensorType = strconv.FormatFloat(item, 'f', -1, 64)
					} else {
						log.Error("populateSensors: Failed to process ", k)
					}
				} else {
					sensor.SensorPropertyList = append(sensor.SensorPropertyList, k)
					if item, ok := v.(string); ok {
						sensor.SensorCharacteristicList = append(
							sensor.SensorCharacteristicList,
							SensorCharacteristic{
								CharacteristicName:  k,
								CharacteristicValue: string(item),
							})
					} else if item, ok := v.(float64); ok {
						sensor.SensorCharacteristicList = append(
							sensor.SensorCharacteristicList,
							SensorCharacteristic{
								CharacteristicName:  k,
								CharacteristicValue: strconv.FormatFloat(item, 'f', -1, 64),
							})
					} else if item, ok := v.(int64); ok {
						sensor.SensorCharacteristicList = append(
							sensor.SensorCharacteristicList,
							SensorCharacteristic{
								CharacteristicName:  k,
								CharacteristicValue: strconv.FormatInt(item, 10),
							})
					} else if item, ok := v.(bool); ok {
						sensor.SensorCharacteristicList = append(
							sensor.SensorCharacteristicList,
							SensorCharacteristic{
								CharacteristicName:  k,
								CharacteristicValue: strconv.FormatBool(item),
							})
					} else if item, ok := v.([]string); ok {
						sensor.SensorCharacteristicList = append(
							sensor.SensorCharacteristicList,
							SensorCharacteristic{
								CharacteristicName:  k,
								CharacteristicValue: strings.Join(item, ","),
							})
					} else if item, ok := v.([]int64); ok {
						log.Error("populateSensors: Failed to convert list of int64 into string: ", item)
					} else if item, ok := v.([]interface{}); ok {
						log.Debug("populateSensors: Got []interface {} for ", k)
						log.Debug("populateSensors: ValueOf ", reflect.ValueOf(item))
						s := SensorCharacteristic{
							CharacteristicName: k,
						}
						var buf bytes.Buffer
						fmt.Fprintf(&buf, "%T", reflect.ValueOf(item))
						s.CharacteristicValue = buf.String()
						sensor.SensorCharacteristicList = append(sensor.SensorCharacteristicList, s)
					} else {
						log.Error("populateSensors: Failed to process ", k)
					}
				}
				// if k == "rn" {
				// 	if item, ok := v.(string); ok {
				// 		sensor.DeviceId = item
				// 	} else {
				// 		log.Error("populateSensors: Failed to process ", k)
				// 	}
				// } else if k == "ri" {
				// 	if item, ok := v.(string); ok {
				// 		sensor.SensorIdentifier = item
				// 	} else {
				// 		log.Error("populateSensors: Failed to process ", k)
				// 	}
				// } else if k == "ty" {
				// 	if item, ok := v.(float64); ok {
				// 		sensor.SensorStatusType = strconv.FormatFloat(item, 'f', -1, 64)
				// 	} else {
				// 		log.Error("populateSensors: Failed to process ", k)
				// 	}
				// } else { // default: if k == "lt" || k == "et" || k == "ct" || k == "st" || k == "pi" || k == "lbl" {
				// 	if item, ok := v.(string); ok {
				// 		sensor.SensorCharacteristicList = append(
				// 			sensor.SensorCharacteristicList,
				// 			SensorCharacteristic{
				// 				CharacteristicName:          k,
				// 				CharacteristicValue:         string(item),
				// 				CharacteristicUnitOfMeasure: nil,
				// 			})
				// 	} else if item, ok := v.(float64); ok {
				// 		sensor.SensorCharacteristicList = append(
				// 			sensor.SensorCharacteristicList,
				// 			SensorCharacteristic{
				// 				CharacteristicName:          k,
				// 				CharacteristicValue:         strconv.FormatFloat(item, 'f', -1, 64),
				// 				CharacteristicUnitOfMeasure: nil,
				// 			})
				// 	} else if item, ok := v.([]string); ok {
				// 		sensor.SensorCharacteristicList = append(
				// 			sensor.SensorCharacteristicList,
				// 			SensorCharacteristic{
				// 				CharacteristicName:          k,
				// 				CharacteristicValue:         strings.Join(item, ","),
				// 				CharacteristicUnitOfMeasure: nil,
				// 			})
				// 	} else {
				// 		log.Error("populateSensors: Failed to process ", k)
				// 	}
				// }
			} // End of 'for' loop
			log.Info("populateSensors: sensor: ", sensor)
			sensorsMap[sensor.SensorIdentifier] = sensor
			sensorsPerPlatformMap[sensor.IotPlatformId] = append(sensorsPerPlatformMap[sensor.IotPlatformId], sensor.SensorIdentifier)
		} // End of 'for' loop

	} // End of 'for' statement
	log.Info("populateSensors: sensorsMap: ", sensorsMap)
	log.Info("populateSensors: sensorsPerPlatformMap: ", sensorsPerPlatformMap)

	if profiling {
		now := time.Now()
		log.Debug("populateSensors: ", now.Sub(profilingTimers["populateSensors"]))
	}

	return nil
}

func (tm *SssMgr) oneM2M_create(sensor SensorDiscoveryInfo, requestedIotPlatformId string, type_ string) (sensorResp SensorDiscoveryInfo, err error) {
	// FIXME FSCOM: requestedIotPlatformId should be useless

	// Build the headers
	var headers = http.Header{}
	headers["Accept"] = []string{headerAccept}
	headers["X-M2M-Origin"] = []string{"C" + requestedIotPlatformId} // FIXME FSCOM How to get it
	headers["X-M2M-RI"] = []string{uuid.New().String()}
	headers["X-M2M-RVI"] = []string{"4"}
	var s string
	if type_ == "AE" {
		s = headerContentType + ";ty=2"
	} else if type_ == "CNT" {
		s = headerContentType + ";ty=4"
	}
	headers["Content-Type"] = []string{s}
	// Build the url and the body
	var url string
	var bodyMap = map[string]map[string]interface{}{}
	// Initialize the entry
	if type_ == "AE" { // FIXME FSCOM Clarify how to map Deviceinfo with oneM2M AE/CNT/fexContainer
		bodyMap["m2m:ae"] = make(map[string]interface{}, 0)
		bodyMap["m2m:ae"]["api"] = "Norg.etsi." + requestedIotPlatformId + "." + sensor.SensorIdentifier
		bodyMap["m2m:ae"]["rn"] = sensor.SensorIdentifier
		bodyMap["m2m:ae"]["rr"] = false
		bodyMap["m2m:ae"]["srv"] = []string{"4"}
		url = "http://" + registeredIotPlatformsMap[requestedIotPlatformId].Address + ":" + strconv.Itoa(int(registeredIotPlatformsMap[requestedIotPlatformId].Port)) + "/" + registeredIotPlatformsMap[requestedIotPlatformId].Name

	} else if type_ == "CNT" {
		bodyMap["m2m:cnt"] = make(map[string]interface{}, 0)
		bodyMap["m2m:cnt"]["mbs"] = 10000
		bodyMap["m2m:cnt"]["mni"] = 10
		bodyMap["m2m:cnt"]["rn"] = sensor.SensorIdentifier
		bodyMap["m2m:cnt"]["srv"] = []string{"4"}
		// Add metadata
		if len(sensor.SensorCharacteristicList) != 0 {
			for _, val := range sensor.SensorCharacteristicList {
				log.Debug("oneM2M_create: Adding CNT metadata: ", val)
				// FIXME FSCOM Add metadata
			} // End of 'for' statement
		}
		url = "http://" + registeredIotPlatformsMap[requestedIotPlatformId].Address + ":" + strconv.Itoa(int(registeredIotPlatformsMap[requestedIotPlatformId].Port)) + "/" + registeredIotPlatformsMap[requestedIotPlatformId].Name
	} else {
		err = errors.New("oneM2M_create: Invalid type")
		log.Error("oneM2M_create: ", err.Error())
		return sensorResp, err
	}
	log.Debug("oneM2M_create: url=", url)
	log.Debug("oneM2M_create: bodyMap=", bodyMap)
	body, err := json.Marshal(bodyMap)
	if err != nil {
		log.Error("oneM2M_create: ", err.Error())
		return sensorResp, err
	}
	log.Debug("oneM2M_create: Request body: ", string(body))
	// Send the request
	response, err := sendRequest("POST", url, headers, bytes.NewBuffer(body), nil, nil, 201)
	if err != nil {
		log.Error("oneM2M_create: ", err.Error())
		return sensorResp, err
	}
	log.Debug("oneM2M_create: response: ", string(response))
	var d map[string]map[string]interface{}
	err = json.Unmarshal(response, &d)
	if err != nil {
		log.Error("oneM2M_create: ", err.Error())
		return sensorResp, err
	}
	log.Debug("oneM2M_create: d: ", d)

	// Add additional entries
	sensorResp, err = tm.oneM2M_deserialize(sensorResp, d)
	if err != nil {
		log.Error("oneM2M_create: ", err.Error())
		return sensorResp, err
	}
	log.Debug("oneM2M_create: sensorResp: ", sensorResp)

	return sensorResp, nil
}

func (tm *SssMgr) oneM2M_discovery(sensor SensorDiscoveryInfo, requestedIotPlatformId string, type_ string) (sensorResp SensorDiscoveryInfo, err error) {
	// FIXME FSCOM: requestedIotPlatformId should be useless

	// 1. Get the list of the AE
	// Build the URL
	url := "http://" + registeredIotPlatformsMap[requestedIotPlatformId].Address + ":" + strconv.Itoa(int(registeredIotPlatformsMap[requestedIotPlatformId].Port)) + "/" + registeredIotPlatformsMap[requestedIotPlatformId].Name
	log.Debug("oneM2M_discovery: url=", url)
	// Build the headers
	var headers = http.Header{}
	headers["Accept"] = []string{headerAccept}
	headers["Content-Type"] = []string{headerContentType}
	headers["X-M2M-Origin"] = []string{"CAdmin"} // FIXME FSCOM How to get it
	headers["X-M2M-RI"] = []string{uuid.New().String()}
	headers["X-M2M-RVI"] = []string{"4"} // FIXME FSCOM How to get it
	// Build the queries
	queries := map[string]string{}
	if type_ == "CN" {
		queries["fu"] = "1" // Filter usage
		queries["ty"] = "4" // Filter on oneM2M CIN for sensor
	} else {
		err = errors.New("oneM2M_discovery: Invalid type")
		log.Error("oneM2M_discovery: ", err.Error())
		return sensorResp, err
	}
	// Send the request
	response, err := sendRequest("GET", url, headers, nil, nil, queries, 200)
	if err != nil {
		log.Error("oneM2M_discovery: ", err.Error())
		return sensorResp, err
	}
	log.Debug("oneM2M_discovery: response: ", string(response))

	var d map[string]map[string]interface{}
	err = json.Unmarshal(response, &d)
	if err != nil {
		log.Error("oneM2M_discovery: ", err.Error())
		return sensorResp, err
	}
	log.Debug("oneM2M_discovery: d: ", d)
	// Add additional entries
	sensorResp, err = tm.oneM2M_deserialize(sensor, d)
	if err != nil {
		log.Error("oneM2M_discovery: ", err.Error())
		return sensorResp, err
	}
	// log.Debug("oneM2M_discovery: sensorResp: ", sensorResp)
	return sensorResp, nil
}

func (tm *SssMgr) oneM2M_get(sensor SensorDiscoveryInfo, requestedIotPlatformId string, type_ string) (sensorResp SensorDiscoveryInfo, err error) {
	// FIXME FSCOM: requestedIotPlatformId should be useless

	if sensor.SensorIdentifier == "" {
		err = errors.New("oneM2M_get: Cannot find \"ri\" value")
		log.Error("oneM2M_get: ", err.Error())
		return sensorResp, err
	}

	// 1. Get the list of the AE
	// Build the URL
	url := "http://" + registeredIotPlatformsMap[requestedIotPlatformId].Address + ":" + strconv.Itoa(int(registeredIotPlatformsMap[requestedIotPlatformId].Port)) + "/" + sensor.SensorIdentifier
	log.Debug("oneM2M_get: url=", url)
	// Build the headers
	var headers = http.Header{}
	headers["Accept"] = []string{headerAccept}
	headers["Content-Type"] = []string{headerContentType}
	headers["X-M2M-Origin"] = []string{"CAdmin"} // FIXME FSCOM How to get it
	headers["X-M2M-RI"] = []string{uuid.New().String()}
	headers["X-M2M-RVI"] = []string{"4"} // FIXME FSCOM How to get it
	// Build the queries
	queries := map[string]string{}
	if type_ == "AE" {
		queries = nil
	} else if type_ == "CN" {
		queries["fu"] = "1" // Filter usage
		queries["ty"] = "4" // Filter on oneM2M CIN for sensor
	} else {
		err = errors.New("oneM2M_get: Invalid type")
		log.Error("oneM2M_get: ", err.Error())
		return sensorResp, err
	}
	// Send the request
	response, err := sendRequest("GET", url, headers, nil, nil, queries, 200)
	if err != nil {
		log.Error("oneM2M_get: ", err.Error())
		return sensorResp, err
	}
	log.Debug("oneM2M_get: response: ", string(response))

	var d map[string]map[string]interface{}
	err = json.Unmarshal(response, &d)
	if err != nil {
		log.Error("oneM2M_get: ", err.Error())
		return sensorResp, err
	}
	log.Debug("oneM2M_get: d: ", d)

	// Add additional entries
	sensorResp, err = tm.oneM2M_deserialize(sensor, d)
	if err != nil {
		log.Error("oneM2M_get: ", err.Error())
		return sensorResp, err
	}
	log.Debug("oneM2M_get: sensorResp: ", sensorResp)
	return sensorResp, nil
}

func (tm *SssMgr) oneM2M_delete(sensor SensorDiscoveryInfo, requestedIotPlatformId string, type_ string) (err error) {
	// FIXME FSCOM: requestedIotPlatformId should be useless

	if sensor.SensorIdentifier == "" {
		err = errors.New("oneM2M_delete: Cannot find \"ri\" value")
		log.Error("oneM2M_delete: ", err.Error())
		return err
	}

	// Build the URL
	url := "http://" + registeredIotPlatformsMap[requestedIotPlatformId].Address + ":" + strconv.Itoa(int(registeredIotPlatformsMap[requestedIotPlatformId].Port)) + "/" + sensor.SensorIdentifier
	log.Debug("oneM2M_delete: url=", url)
	// Build the headers
	var headers = http.Header{}
	headers["Accept"] = []string{headerAccept}
	headers["Content-Type"] = []string{headerContentType}
	headers["X-M2M-Origin"] = []string{"C" + requestedIotPlatformId} // FIXME FSCOM How to get it
	headers["X-M2M-RI"] = []string{uuid.New().String()}
	headers["X-M2M-RI"] = []string{uuid.New().String()}
	headers["X-M2M-RVI"] = []string{"4"}
	// Send the request
	_, err = sendRequest("DELETE", url, headers, nil, nil, nil, 200)
	if err != nil {
		log.Error("oneM2M_delete: ", err.Error())
		return err
	}

	return nil
}

func (tm *SssMgr) oneM2M_subscribe_discovery_event(requestedIotPlatformId string) (err error) {

	return nil
}

func (tm *SssMgr) oneM2M_deserialize(sensor SensorDiscoveryInfo, response map[string]map[string]interface{}) (sensorResp SensorDiscoveryInfo, err error) {
	sensorResp = sensor // Same data structure

	log.Debug("oneM2M_deserialize: type(response): ", reflect.TypeOf(response))
	log.Debug("oneM2M_deserialize: len(response): ", len(response))
	log.Debug("oneM2M_deserialize: response: ", response)

	if val, ok := response["m2m:ae"]; ok {
		log.Debug("oneM2M_deserialize: val: ", val)
	} else {
		log.Error("oneM2M_deserialize: CharacteristicName not found")
	}

	for i, m := range response {
		log.Debug("==> ", i, " value is ", m)
		// m is a map[string]interface.
		// loop over keys and values in the map.
		for k, v := range m {
			log.Debug(k, " value is ", v)
			log.Debug("oneM2M_deserialize: type(v): ", reflect.TypeOf(v))

			if k == "ri" {
				if item, ok := v.(string); ok {
					sensor.SensorIdentifier = item
				} else {
					log.Error("populateSensors: Failed to process ", k)
				}
			} else if k == "ty" {
				if item, ok := v.(string); ok {
					sensor.SensorType = item
				} else {
					log.Error("populateSensors: Failed to process ", k)
				}
			} else {
				if item, ok := v.(string); ok {
					sensorResp.SensorCharacteristicList = append(
						sensorResp.SensorCharacteristicList,
						SensorCharacteristic{
							CharacteristicName:  k,
							CharacteristicValue: string(item),
						})
				} else if item, ok := v.(float64); ok {
					sensorResp.SensorCharacteristicList = append(
						sensorResp.SensorCharacteristicList,
						SensorCharacteristic{
							CharacteristicName:  k,
							CharacteristicValue: strconv.FormatFloat(item, 'f', -1, 64),
						})
				} else if item, ok := v.(int64); ok {
					sensorResp.SensorCharacteristicList = append(
						sensorResp.SensorCharacteristicList,
						SensorCharacteristic{
							CharacteristicName:  k,
							CharacteristicValue: strconv.FormatInt(item, 10),
						})
				} else if item, ok := v.(bool); ok {
					sensorResp.SensorCharacteristicList = append(
						sensorResp.SensorCharacteristicList,
						SensorCharacteristic{
							CharacteristicName:  k,
							CharacteristicValue: strconv.FormatBool(item),
						})
				} else if item, ok := v.([]string); ok {
					sensorResp.SensorCharacteristicList = append(
						sensorResp.SensorCharacteristicList,
						SensorCharacteristic{
							CharacteristicName:  k,
							CharacteristicValue: strings.Join(item, ","),
						})
				} else if item, ok := v.([]int64); ok {
					log.Error("oneM2M_deserialize: Failed to convert list of int64 into string: ", item)
				} else if item, ok := v.([]interface{}); ok {
					log.Debug("populateSensors: Got []interface {} for ", k)
					log.Debug("populateSensors: ValueOf ", reflect.ValueOf(item))
					s := SensorCharacteristic{
						CharacteristicName: k,
					}
					var buf bytes.Buffer
					fmt.Fprintf(&buf, "%T", item)
					s.CharacteristicValue = buf.String()
					sensor.SensorCharacteristicList = append(sensor.SensorCharacteristicList, s)
				} else {
					log.Error("oneM2M_deserialize: Failed to process: ", k)
				}
			}
		} // End of 'for' loop

	} // End of 'for' loop

	return sensorResp, nil
}

func sendRequest(method string, url string, headers http.Header, body io.Reader, vars map[string]string, query map[string]string, code int) ([]byte, error) {
	//log.Debug(">>> sendRequest: url: ", url)
	//log.Debug(">>> sendRequest: headers: ", headers)

	req, err := http.NewRequest(method, url, body)
	if err != nil || req == nil {
		return nil, err
	}
	if vars != nil {
		req = mux.SetURLVars(req, vars)
	}
	if query != nil {
		q := req.URL.Query()
		for k, v := range query {
			q.Add(k, v)
		}
		req.URL.RawQuery = q.Encode()
	}
	req.Header = headers
	req.Close = true

	//log.Debug("sendRequest: req: ", req)
	rr, err := http.DefaultClient.Do(req)
	if err != nil {
		return nil, err
	}

	// Check the status code is what we expect.
	//log.Debug("sendRequest: rr: ", rr)
	if status := rr.StatusCode; status != code {
		s := fmt.Sprintf("Wrong status code - got %v want %v", status, code)
		return nil, errors.New(s)
	}
	responseData, err := ioutil.ReadAll(rr.Body)
	if err != nil {
		return nil, err
	}
	//log.Debug("sendRequest: responseData: ", responseData)

	return responseData, nil
}
