package config

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

func initBannedPlayer(serverFolder string) BannedPlayer {
	jsonFile, err := os.Open(serverFolder + "/banned-players.json")
	if err != nil {
		fmt.Println(err)
	}
	byte, _ := ioutil.ReadAll(jsonFile)
	var dataArray BannedPlayer
	json.Unmarshal(byte, &dataArray)
	return dataArray
}

//ReadAllBannedPlayers is exported function
func (mch *Handler) ReadAllBannedPlayers() BannedPlayer {
	return mch.bannedPlayers
}

//WriteBannedPlayer is exported function
func (mch *Handler) WriteBannedPlayer(UUID string, Name string, Created string, Source string, Expires string, Reason string) bool {
	newItem := BannedPlayer{}
	newItem = append(newItem, struct {
		UUID    string `json:"uuid"`
		Name    string `json:"name"`
		Created string `json:"created"`
		Source  string `json:"source"`
		Expires string `json:"expires"`
		Reason  string `json:"reason"`
	}{UUID, Name, Created, Source, Expires, Reason})
	mch.bannedPlayers = append(mch.bannedPlayers, newItem...)
	return true
}

//ReadBannedPlayer is exported function
func (mch *Handler) ReadBannedPlayer(search string, field string) BannedPlayer {
	var list BannedPlayer
	for _, item := range mch.bannedPlayers {
		fieldValue := ""
		switch strings.ToLower(field) {
		case "uuid":
			fieldValue = item.UUID
		case "name":
			fieldValue = item.Name
		case "created":
			fieldValue = item.Created
		case "source":
			fieldValue = item.Source
		case "expires":
			fieldValue = item.Expires
		case "reason":
			fieldValue = item.Reason
		default:
			fieldValue = ""
		}
		if fieldValue == search {
			list = append(list, item)
		}
	}
	return list
}

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

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