/*
 * Copyright (c) 2020  InterDigital Communications, Inc
 *
 * 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.
 *
 * MEEP Demo App API
 *
 * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
 *
 * API version: 0.0.1
 * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)
 */

package server

import (
	"encoding/json"
	"fmt"
	"net/http"

	"github.com/gorilla/mux"
)

func CreateUeState(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")

	vars := mux.Vars(r)
	ueId := vars["ueId"]

	val := getUe(ueId)

	if val == nil {
		addUe(ueId)
		w.WriteHeader(http.StatusOK)
	} else { //ue already exists, just restart the counter
		restartUe(ueId)
		w.WriteHeader(http.StatusOK)
	}
}

func DeleteUeState(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")

	vars := mux.Vars(r)
	ueId := vars["ueId"]

	val := getUe(ueId)

	if val != nil {
		deleteUe(ueId)
		w.WriteHeader(http.StatusOK)
	} else {
		w.WriteHeader(http.StatusNotFound)
	}

}

func GetUeState(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")

	vars := mux.Vars(r)
	ueId := vars["ueId"]

	val := getUe(ueId)

	if val != nil {

		// Format response
		jsonResponse, err := json.Marshal(val)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		// Send response
		w.WriteHeader(http.StatusOK)
		fmt.Fprint(w, string(jsonResponse))

	} else {
		w.WriteHeader(http.StatusNotFound)
	}
}

func UpdateUeState(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")

	vars := mux.Vars(r)
	ueId := vars["ueId"]

	val := getUe(ueId)

	if val != nil {
		// Retrieve UeState from request body
		ueState := new(UeState)
		decoder := json.NewDecoder(r.Body)
		err := decoder.Decode(&ueState)
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}

		//update values in the state object
		//val.Duration -- no need to update this one, we keep as is
		val.TrafficBw = ueState.TrafficBw
		updateUe(ueId, *val)
		w.WriteHeader(http.StatusOK)

	} else {
		w.WriteHeader(http.StatusNotFound)
		return
	}
}
