package ldap

import (
	"encoding/json"
	"github.com/astaxie/beego/logs"
	"github.com/go-ldap/ldap/v3"
	"nginx-ui/server/models"
	"strings"
	"time"
)

func modifyLDAPUser(user *models.LdapUser, entry *ldap.Entry) {
	user.LastSyncDate = time.Now()
	user.Password = entry.GetAttributeValue("userPassword")
	user.UserName = entry.GetAttributeValue("cn")
	user.Mail = entry.GetAttributeValue("mail")
	user.DN = entry.DN
	var organizeList []string
	items := strings.Split(user.DN, ",")
	for _, item := range items {
		if !strings.HasPrefix(item, "cn=") {
			organizeList = append(organizeList, item)
		}
	}
	user.Organize = strings.Join(organizeList, ",")
}

func createUser(entry *ldap.Entry) models.LdapUser {
	user := models.LdapUser{
		Account: entry.GetAttributeValue("uid"),
	}
	modifyLDAPUser(&user, entry)
	jsonBytes, err := json.Marshal(entry.Attributes)
	if err != nil {
		logs.Error("marshal fail : %v", err)
		user.Remark = "attributes marshal fail: " + err.Error()
	} else {
		user.Attributes = string(jsonBytes)
	}
	return user
}

func createLocalUser(user *models.User, from *models.LdapUser) {
	user.Password = from.Password
	user.Account = from.Account
	user.Nickname = from.UserName
	user.Source = "LDAP"
}