/*
 * Copyright (c) 2022  ETSI STF 625
 *
 * 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 sbi

import (
	"sync"
	//"time"

	//dataModel "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-data-model"
	tm "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-dai-mgr"
	gc "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-gis-cache"
	log "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-logger"
	met "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-metrics"
	mod "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-model"
	mq "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-mq"
	sam "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-swagger-api-mgr"
)

const moduleName string = "meep-dai-sbi"

var metricStore *met.MetricStore
var redisAddr string = "meep-redis-master.default.svc.cluster.local:6379"
var influxAddr string = "http://meep-influxdb.default.svc.cluster.local:8086"

const postgresUser = "postgres"
const postgresPwd = "pwd"

type SbiCfg struct {
	ModuleName               string
	SandboxName              string
	MepName                  string
	RedisAddr                string
	InfluxAddr               string
	PostgisHost              string
	PostgisPort              string
	Locality                 []string
	ScenarioNameCb           func(string)
	AppInfoList              func(tm.AppInfoList)
	NotifyAppContextDeletion func(string, string)
	CleanUpCb                func()
}

type DaiSbi struct {
	moduleName      string
	sandboxName     string
	mepName         string
	scenarioName    string
	localityEnabled bool
	locality        map[string]bool
	mqLocal         *mq.MsgQueue
	handlerId       int
	apiMgr          *sam.SwaggerApiMgr
	activeModel     *mod.Model
	gisCache        *gc.GisCache
	daiMgr          *tm.DaiMgr
	//refreshTicker        *time.Ticker
	updateAppInfoCB      func(tm.AppInfoList)
	updateScenarioNameCB func(string)
	cleanUpCB            func()
	mutex                sync.Mutex
}

var sbi *DaiSbi = nil

// Init - DAI Service SBI initialization
func Init(cfg SbiCfg) (err error) {
	// Create new SBI instance
	if sbi != nil {
		sbi = nil
	}
	sbi = new(DaiSbi)
	sbi.moduleName = cfg.ModuleName
	sbi.sandboxName = cfg.SandboxName
	sbi.mepName = cfg.MepName
	sbi.scenarioName = ""
	sbi.updateAppInfoCB = cfg.AppInfoList
	sbi.updateScenarioNameCB = cfg.ScenarioNameCb
	sbi.cleanUpCB = cfg.CleanUpCb
	redisAddr = cfg.RedisAddr
	influxAddr = cfg.InfluxAddr

	// Fill locality map
	if len(cfg.Locality) > 0 {
		sbi.locality = make(map[string]bool)
		for _, locality := range cfg.Locality {
			sbi.locality[locality] = true
		}
		sbi.localityEnabled = true
	} else {
		sbi.localityEnabled = false
	}

	// Create message queue
	sbi.mqLocal, err = mq.NewMsgQueue(mq.GetLocalName(sbi.sandboxName), sbi.moduleName, sbi.sandboxName, cfg.RedisAddr)
	if err != nil {
		log.Error("Failed to create Message Queue with error: ", err)
		return err
	}
	log.Info("Message Queue created")

	// Create Swagger API Manager
	sbi.apiMgr, err = sam.NewSwaggerApiMgr(sbi.moduleName, sbi.sandboxName, sbi.mepName, sbi.mqLocal)
	if err != nil {
		log.Error("Failed to create Swagger API Manager. Error: ", err)
		return err
	}
	log.Info("Swagger API Manager created")

	// Create new active scenario model
	modelCfg := mod.ModelCfg{
		Name:      "activeScenario",
		Namespace: sbi.sandboxName,
		Module:    moduleName,
		UpdateCb:  nil,
		DbAddr:    cfg.RedisAddr,
	}
	sbi.activeModel, err = mod.NewModel(modelCfg)
	if err != nil {
		log.Error("Failed to create model: ", err.Error())
		return err
	}

	// Connect to GIS cache
	sbi.gisCache, err = gc.NewGisCache(sbi.sandboxName, cfg.RedisAddr)
	if err != nil {
		log.Error("Failed to GIS Cache: ", err.Error())
		return err
	}
	log.Info("Connected to GIS Cache")

	// Connect to DAI Manager
	sbi.daiMgr, err = tm.NewDaiMgr(sbi.moduleName, sbi.sandboxName, postgresUser, postgresPwd, cfg.PostgisHost, cfg.PostgisPort)
	if err != nil {
		log.Error("Failed connection to VIS Traffic Manager: ", err)
		return err
	}
	log.Info("Connected to DAI Manager")

	// Delete any old tables
	_ = sbi.daiMgr.DeleteTables()

	// Create new tables
	err = sbi.daiMgr.CreateTables()
	if err != nil {
		log.Error("Failed to create tables: ", err)
		return err
	}
	log.Info("Created new DAI DB tables")

	err = sbi.daiMgr.SimulateExistingApplication()
	if err != nil {
		log.Error("Failed to load simulating data: ", err)
		return err
	}
	log.Info("Created existing application")

	// Initialize service
	processActiveScenarioUpdate()

	return nil
}

// Run - MEEP DAI execution
func Run() (err error) {

	// Start Swagger API Manager (provider)
	err = sbi.apiMgr.Start(true, false)
	if err != nil {
		log.Error("Failed to start Swagger API Manager with error: ", err.Error())
		return err
	}
	log.Info("Swagger API Manager started")

	// Add module Swagger APIs
	err = sbi.apiMgr.AddApis()
	if err != nil {
		log.Error("Failed to add Swagger APIs with error: ", err.Error())
		return err
	}
	log.Info("Swagger APIs successfully added")

	// Register Message Queue handler
	handler := mq.MsgHandler{Handler: msgHandler, UserData: nil}
	sbi.handlerId, err = sbi.mqLocal.RegisterHandler(handler)
	if err != nil {
		log.Error("Failed to register message queue handler: ", err.Error())
		return err
	}

	// Start refresh loop
	//startRefreshTicker()

	return nil
}

func Stop() (err error) {
	if sbi == nil {
		return
	}

	// Stop refresh loop
	//stopRefreshTicker()

	if sbi.mqLocal != nil {
		sbi.mqLocal.UnregisterHandler(sbi.handlerId)
	}

	if sbi.apiMgr != nil {
		// Remove APIs
		err = sbi.apiMgr.RemoveApis()
		if err != nil {
			log.Error("Failed to remove APIs with err: ", err.Error())
			return err
		}
	}

	// Delete DAI Traffic Manager
	if sbi.daiMgr != nil {
		err = sbi.daiMgr.DeleteDaiMgr()
		if err != nil {
			log.Error(err.Error())
			return err
		}
	}

	return nil
}

// Message Queue handler
func msgHandler(msg *mq.Msg, userData interface{}) {
	switch msg.Message {
	case mq.MsgScenarioActivate:
		log.Debug("RX MSG: ", mq.PrintMsg(msg))
		processActiveScenarioUpdate()
	case mq.MsgScenarioUpdate:
		log.Debug("RX MSG: ", mq.PrintMsg(msg))
		processActiveScenarioUpdate()
	case mq.MsgScenarioTerminate:
		log.Debug("RX MSG: ", mq.PrintMsg(msg))
		processActiveScenarioTerminate()
	default:
		log.Trace("Ignoring unsupported message: ", mq.PrintMsg(msg))
	}
}

func processActiveScenarioTerminate() {
	log.Debug("processActiveScenarioTerminate")

	// Sync with active scenario store
	sbi.activeModel.UpdateScenario()

	// Flush all Traffic Manager tables
	_ = sbi.daiMgr.DeleteTables()

	sbi.cleanUpCB()
}

func processActiveScenarioUpdate() {

	sbi.mutex.Lock()
	defer sbi.mutex.Unlock()

	log.Debug("processActiveScenarioUpdate")

	/*prevApps := []string{}
	prevAppList := sbi.activeModel.GetNodeNames("UE-APP", "EDGE-APP")
	for _, app := range prevAppList {
		// Make sure App is in Locality
		if isAppConnected(app) && isInLocality(app) {
			prevApps = append(prevApps, app)
		}
	}
	log.Debug("==> prevApps: ", prevApps)*/

	// Sync with active scenario store
	sbi.activeModel.UpdateScenario()

	scenarioName := sbi.activeModel.GetScenarioName()

	// Connect to Metric Store
	sbi.updateScenarioNameCB(scenarioName)

	if scenarioName != sbi.scenarioName {
		sbi.scenarioName = scenarioName
		var err error

		metricStore, err = met.NewMetricStore(scenarioName, sbi.sandboxName, influxAddr, redisAddr)
		if err != nil {
			log.Error("Failed connection to metric-store: ", err)
		}
	}
}

/*func startRefreshTicker() {
	log.Info("Starting refresh loop")
	sbi.refreshTicker = time.NewTicker(1000 * time.Millisecond)
	go func() {
		for range sbi.refreshTicker.C {
			_ = refreshAppList()
		}
	}()
}

func stopRefreshTicker() {
	if sbi.refreshTicker != nil {
		sbi.refreshTicker.Stop()
		sbi.refreshTicker = nil
		log.Info("Refresh loop stopped")
	}
}

// refreshAppList - Update AppList data struct
func refreshAppList() error {
	sbi.mutex.Lock()
	defer sbi.mutex.Unlock()
	log.Info("Update AppList data struct")

	// Build the list of all application
	appInfo, err := sbi.daiMgr.GetAllAppList()
	if err != nil {
		log.Error(err.Error())
		return err
	}
	log.Debug("appContextMap: ", appInfo)

	// Store it into Redis

	return nil
}*/

// ETSI GS MEC 016 V2.2.1 (2020-04) Clause 7.3.3.1 GET
func GetApplicationListAppList(appNames []string) (appListSbi *map[string]*tm.AppInfoList, err error) {
	log.Debug(">>> GetApplicationListAppList: ", appNames)

	appListSbi, err = GetAllListAppList()
	if err != nil {
		log.Error(err.Error())
		return nil, err
	}

	// Apply criteria
	if len(appNames) == 0 {
		log.Debug("<<< GetApplicationListAppList: ", appListSbi)
		return appListSbi, nil
	}

	filteredAppListSbi := make(map[string]*tm.AppInfoList)
	for _, appName := range appNames {
		// Remove quotes
		if appName != "" {
			appName = appName[1 : len(appName)-1] // Remove quotes
		}
		// Search for the entry
		for _, item := range *appListSbi {
			if item.AppName == appName {
				filteredAppListSbi[appName] = item
			}
		} // End of 'for' statement
	} // End of 'for' statement

	log.Debug("<<< GetApplicationListAppList: ", filteredAppListSbi)
	return &filteredAppListSbi, nil
}

func GetAllListAppList() (appListSbi *map[string]*tm.AppInfoList, err error) {

	// Get list of application
	appInfoList, err := sbi.daiMgr.GetAllAppInfoListEntry()
	if err != nil {
		log.Error(err.Error())
		return nil, err
	}
	appListSbi = &appInfoList
	log.Debug("appListSbi: ", appListSbi)
	log.Debug("len(appListSbi): ", len(*appListSbi))

	// appListSbi = new(tm.tm.AppInfoList)
	// appListSbi.AppList = make([]tm.AppInfoSbi, len(obj))
	// i := 0
	// for _, item := range obj {
	// 	//log.Debug("obj: i=", i, " item= ", item)
	// 	//log.Debug("===> item.AppDId= ", item.AppDId)
	// 	appListSbi.AppList[i].AppDId = item.AppDId
	// 	appListSbi.AppList[i].AppName = item.AppName
	// 	appListSbi.AppList[i].AppProvider = item.AppProvider
	// 	appListSbi.AppList[i].AppSoftVersion = item.AppSoftVersion
	// 	appListSbi.AppList[i].AppDVersion = item.AppDVersion
	// 	appListSbi.AppList[i].AppDescription = item.AppDescription

	// 	if len(item.AppLocation) != 0 {
	// 		appListSbi.AppList[i].AppLocation = make([]tm.LocationConstraintsItem, len(item.AppLocation))
	// 		for j, item1 := range item.AppLocation {
	// 			//log.Debug("item1: ", item1)
	// 			if item1.Area != nil {
	// 				appListSbi.AppList[i].AppLocation[j].Area = new(tm.Polygon)
	// 				appListSbi.AppList[i].AppLocation[j].Area.Coordinates = item1.Area.Coordinates
	// 			} else {
	// 				appListSbi.AppList[i].AppLocation[j].Area = nil
	// 			}
	// 			if item1.CivicAddressElement != nil {
	// 				appListSbi.AppList[i].AppLocation[j].CivicAddressElement = make([]tm.CivicAddressElementItem, len(*item1.CivicAddressElement))
	// 				for k, cv := range *item1.CivicAddressElement {
	// 					appListSbi.AppList[i].AppLocation[j].CivicAddressElement[k].CaType = cv.CaType
	// 					appListSbi.AppList[i].AppLocation[j].CivicAddressElement[k].CaValue = cv.CaValue
	// 				}
	// 			} else {
	// 				appListSbi.AppList[i].AppLocation[j].CivicAddressElement = nil
	// 			}
	// 			if item1.CountryCode != nil {
	// 				appListSbi.AppList[i].AppLocation[j].CountryCode = new(string)
	// 				appListSbi.AppList[i].AppLocation[j].CountryCode = item1.CountryCode
	// 			} else {
	// 				appListSbi.AppList[i].AppLocation[j].CountryCode = nil
	// 			}
	// 		} // End of 'for' statement
	// 	}

	// 	if len(item.AppCharcs) != 0 {
	// 		appListSbi.AppList[i].AppCharcs = make([]tm.AppCharcs, len(item.AppCharcs))
	// 		for j, item2 := range item.AppCharcs {
	// 			//log.Debug("item2: ", item2)
	// 			if item2.Memory != nil {
	// 				appListSbi.AppList[i].AppCharcs[j].Memory = new(uint32)
	// 				*appListSbi.AppList[i].AppCharcs[j].Memory = *item2.Memory
	// 			} else {
	// 				appListSbi.AppList[i].AppCharcs[j].Memory = nil
	// 			}
	// 			if item2.Storage != nil {
	// 				appListSbi.AppList[i].AppCharcs[j].Storage = new(uint32)
	// 				*appListSbi.AppList[i].AppCharcs[j].Storage = *item2.Storage
	// 			} else {
	// 				appListSbi.AppList[i].AppCharcs[j].Storage = nil
	// 			}
	// 			if item2.Latency != nil {
	// 				appListSbi.AppList[i].AppCharcs[j].Latency = new(uint32)
	// 				*appListSbi.AppList[i].AppCharcs[j].Latency = *item2.Latency
	// 			} else {
	// 				appListSbi.AppList[i].AppCharcs[j].Latency = nil
	// 			}
	// 			if item2.Bandwidth != nil {
	// 				appListSbi.AppList[i].AppCharcs[j].Bandwidth = new(uint32)
	// 				*appListSbi.AppList[i].AppCharcs[j].Bandwidth = *item2.Bandwidth
	// 			} else {
	// 				appListSbi.AppList[i].AppCharcs[j].Bandwidth = nil
	// 			}
	// 			if item2.ServiceCont != nil {
	// 				appListSbi.AppList[i].AppCharcs[j].ServiceCont = new(uint32)
	// 				*appListSbi.AppList[i].AppCharcs[j].ServiceCont = *item2.ServiceCont
	// 			} else {
	// 				appListSbi.AppList[i].AppCharcs[j].ServiceCont = nil
	// 			}
	// 		} // End of 'for' statement
	// 	}

	// 	// Process next item
	// 	i = i + 1
	// } // End of 'for' statement

	//sbi.updateAppInfoCB(appListSbi)
	return appListSbi, nil
}

func CreateAppContext(appContextSbi *tm.AppContext) (appContextSbi_ *tm.AppContext, err error) {
	log.Debug(">>> CreateAppContext: ", appContextSbi)

	appContextSbi_, err = sbi.daiMgr.CreateAppContext(appContextSbi)
	if err != nil {
		log.Error(err.Error())
		return nil, err
	}
	log.Debug("CreateAppContext: appContext: ", appContextSbi_)

	return appContextSbi_, nil
}

func DeleteAppContext(contextId string) (err error) {
	log.Debug(">>> DeleteAppContext: ", contextId)

	err = sbi.daiMgr.DeleteAppContext(contextId)
	if err != nil {
		log.Error(err.Error())
		return err
	}

	return nil
}

func PutAppContext(appContextSbi tm.AppContext) (err error) {
	log.Debug(">>> PutAppContext: ", appContextSbi)
	log.Debug(">>> PutAppContext: ", *appContextSbi.ContextId)

	err = sbi.daiMgr.PutAppContext(appContextSbi)
	if err != nil {
		log.Error(err.Error())
		return err
	}

	return nil
}

/*func notifyAppContextDeletion(appContextSbi tm.AppContext) (err error) {
	log.Debug(">>> notifyAppContextDeletion: ", appContextSbi)
	log.Debug(">>> notifyAppContextDeletion: ", *appContextSbi.ContextId)

	return nil
}

func isAppConnected(app string) bool {
	parentNode := sbi.activeModel.GetNodeParent(app)
	if parentNode != nil {
		pl := parentNode.(*dataModel.PhysicalLocation)
		return pl.Connected
	}
	return false
}

func isInLocality(name string) bool {
	if sbi.localityEnabled {
		ctx := sbi.activeModel.GetNodeContext(name)
		if ctx == nil {
			log.Error("Error getting context for: " + name)
			return false
		}
		if _, found := sbi.locality[ctx.Parents[mod.Zone]]; !found {
			return false
		}
	}
	return true
}*/
