package config

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

func initBannedIP(serverFolder string) BannedIP {

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

//ReadAllBannedIPs is exported function
func (mch *Handler) ReadAllBannedIPs() BannedIP {
	return mch.bannedIPs
}

//WriteBannedIP is exported function
func (mch *Handler) WriteBannedIP(IP string, Created string, Source string, Expires string, Reason string) bool {
	newItem := BannedIP{}
	newItem = append(newItem, struct {
		IP      string `json:"ip"`
		Created string `json:"created"`
		Source  string `json:"source"`
		Expires string `json:"expires"`
		Reason  string `json:"reason"`
	}{IP, Created, Source, Expires, Reason})
	mch.bannedIPs = append(mch.bannedIPs, newItem...)
	return true
}

//ReadBannedIP is exported function
func (mch *Handler) ReadBannedIP(search string, field string) BannedIP {
	var list BannedIP
	for _, item := range mch.bannedIPs {
		fieldValue := ""
		switch strings.ToLower(field) {
		case "ip":
			fieldValue = item.IP
		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
}

//RemoveBannedIP is exported function
func (mch *Handler) RemoveBannedIP(search string, field string) bool {
	for i, item := range mch.bannedIPs {
		fieldValue := ""
		switch strings.ToLower(field) {
		case "ip":
			fieldValue = item.IP
		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.bannedIPs)-1 != i {
				mch.bannedIPs = append(mch.bannedIPs[:i], mch.bannedIPs[i+1])
			} else {
				// if it is the last item, just remove it
				mch.bannedIPs = mch.bannedIPs[:i]
			}
		}
	}
	return true
}

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