package validation

import (
	"strings"

	"bitbucket.org/nemt/nemt-portal-api/application/viewmodel"
	"bitbucket.org/nemt/nemt-portal-api/infra/errors"
)

func characterIsUpperCase(character rune) bool {
	return (character >= 65) && (character <= 90)
}

func characterIsLowerCase(character rune) bool {
	return (character >= 97) && (character <= 122)
}

func characterIsNumber(character rune) bool {
	return (character >= 48) && (character <= 57)
}

func ValidatePassword(user *viewmodel.User) []errors.ValidationError {
	var result []errors.ValidationError

	userOrganizationName := ""
	if len(user.Organizations) > 0 {
		userOrganizationName = user.Organizations[0].Name
	}

	if len(user.Pass) < 8 {
		result = append(result, errors.ValidationError{Field: "password", Message: "Password must be at least 8 characters."})
	}

	if strings.Contains(user.Pass, user.First) {
		result = append(result, errors.ValidationError{Field: "password", Message: "Password cannot include your First Name."})
	}

	if strings.Contains(user.Pass, user.Last) {
		result = append(result, errors.ValidationError{Field: "password", Message: "Password cannot include your Last Name."})
	}

	if len(userOrganizationName) > 0 {
		if strings.Contains(user.Pass, userOrganizationName) {
			result = append(result, errors.ValidationError{Field: "password", Message: "Password cannot include your Organization Name."})
		}
	}

	containsUpperCaseLetter := false
	containsLowerCaseLetter := false
	containsNumber := false

	for _, character := range user.Pass {
		containsUpperCaseLetter = containsUpperCaseLetter || characterIsUpperCase(character)
		containsLowerCaseLetter = containsLowerCaseLetter || characterIsLowerCase(character)
		containsNumber = containsNumber || characterIsNumber(character)
	}

	if !containsUpperCaseLetter || !containsLowerCaseLetter || !containsNumber {
		result = append(result, errors.ValidationError{Field: "password", Message: "Password must contain one of EACH :"})
		result = append(result, errors.ValidationError{Field: "password-tab", Message: "an uppercase letter"})
		result = append(result, errors.ValidationError{Field: "password-tab", Message: "a lowercase letter"})
		result = append(result, errors.ValidationError{Field: "password-tab", Message: "a number"})
	}

	return result
}
