package main

import (
	"fmt"
	"math/rand"
	"os"

	ldap "github.com/go-ldap/ldap/v3"
	"github.com/sirupsen/logrus"
)

const maxlength_generateName, minlength_generateName = 25, 3

const bindusername = "cn=admin,dc=deuxfleurs,dc=fr"
const adresse = "127.0.0.1"
const port = 1389

var logging = logrus.New()

const seed = 654258

var R = rand.New(rand.NewSource(seed))

var bindpassword = "sf7yO52NCuE"

//Handler just to facilite the print error
func PrintError(LDAPError error) {
	if LDAPError != nil {
		logging.Fatal(LDAPError)
	}
}

//Generate an unique name, which store in all_names
func (inst *instance) GenerateName() (name string) {
	alphabet := []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
		"w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y",
		"Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "é", "è", "ê", "ë", "à", "@", "â", "ä", "û", "ü", "ù", "$", "£", "%", "ø", "€"}
	length := R.Intn(maxlength_generateName) + minlength_generateName

	//Check if this name not exist already
	//Lock thhis variable because she is hared with other goroutine
	allNames.mu.Lock()
	for only_one := true; only_one; _, only_one = allNames.cn[name] {
		//Create the name
		for i := 0; i < length; i++ {
			name += alphabet[R.Intn(len(alphabet))]
		}

	}
	//Add the new name in the map to store this one
	allNames.cn[name] = struct{}{}
	allNames.mu.Unlock()
	logging.Debug(fmt.Sprintf("Name generated: %s.", name))
	return
}

//Transform attributes in map format to the struct attributes
func MapAttToStruct(att map[string][]string) []attributes {
	resultat := []attributes{}
	for key, value := range att {
		logging.Debug(fmt.Sprintf("Transform: key: %s, values: %s to attributes struct.\n", key, value))
		resultat = append(resultat, attributes{
			Name: key,
			Data: value,
		})
	}
	return resultat
}

func Connect() (*ldap.Conn, error) {
	l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", adresse, port))
	if err != nil {
		return nil, err
	}

	if key, ok := os.LookupEnv("BOTTIN_DEFAULT_ADMIN_PW"); ok {
		bindpassword = key
	}
	//l.Debug.Enable(true)
	err = l.Bind(bindusername, bindpassword)
	logging.Debug("Connection succesful")
	return l, err
}

//Handler to get only attributes names
func getNamesAtt(dat data_DN) []string {
	resultat := []string{}
	for _, values := range dat.Attributes {
		resultat = append(resultat, values.Name)
	}
	return resultat
}

//Handler to compare slice string
func CompareSliceString(string1, string2 []string) bool {
	if len(string1) != len(string2) {
		return false
	} else {
		for index := range string1 {
			if string1[index] != string2[index] {
				return false
			}
		}
	}
	return true
}

//Handler to remove an element in slice string
func DeleteElementSliceString(s string, sSlice []string) []string {

	for index, value := range sSlice {
		if value == s {
			sSlice[index] = sSlice[len(sSlice)-1]
			return sSlice[:len(sSlice)-1]
		}
	}
	return sSlice
}

//Get attributes entry values bottin bug
func GetAttributeValuesBottin(ent *ldap.Entry, name string) (res []string) {
	for _, val := range ent.Attributes {
		if val.Name == name {
			res = append(res, val.Values...)
		}
	}
	return
}
