package config

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"strings"
)

func initWhitelist(serverFolder string) Whitelist {

	jsonFile, err := os.Open(serverFolder + "whitelist.json")
	if err != nil {
		fmt.Println(err)
	}
	byte, _ := ioutil.ReadAll(jsonFile)
	var dataArray Whitelist
	json.Unmarshal(byte, &dataArray)
	return dataArray
}

//ReadAllWhitelists is exported function
func (mch *Handler) ReadAllWhitelists() Whitelist {
	return mch.whitelists
}

//WriteWhitelist is exported function
func (mch *Handler) WriteWhitelist(UUID string, Name string) bool {
	newItem := Whitelist{}
	newItem = append(newItem, struct {
		UUID string `json:"uuid"`
		Name string `json:"name"`
	}{UUID, Name})
	mch.whitelists = append(mch.whitelists, newItem...)
	return true
}

//ReadWhitelist is exported function
func (mch *Handler) ReadWhitelist(search string, field string) Whitelist {
	var list Whitelist
	for _, item := range mch.whitelists {
		fieldValue := ""
		switch strings.ToLower(field) {
		case "uuid":
			fieldValue = item.UUID
		case "name":
			fieldValue = item.Name
		default:
			fieldValue = ""
		}
		if fieldValue == search {
			list = append(list, item)
		}
	}
	return list
}

//RemoveWhitelist is exported function
func (mch *Handler) RemoveWhitelist(search string, field string) bool {
	for i, item := range mch.whitelists {
		fieldValue := ""
		switch strings.ToLower(field) {
		case "uuid":
			fieldValue = item.UUID
		case "name":
			fieldValue = item.Name
		default:
			fieldValue = ""
		}
		if fieldValue == search {
			if len(mch.ops)-1 != i {
				mch.whitelists = append(mch.whitelists[:i], mch.whitelists[i+1])
			} else {
				// if it is the last item, just remove it
				mch.whitelists = mch.whitelists[:i]
			}
		}
	}
	return true
}

//SaveAllWhitelists is exported function
func (mch *Handler) SaveAllWhitelists() bool {
	JSON, _ := json.Marshal(mch.whitelists)
	err := ioutil.WriteFile(mch.serverFolder+"/whitelist.json", JSON, 0777)
	if err != nil {
		fmt.Println(err)
	}
	return true
}
