package auxhttp

import (
	"encoding/base64"
	"errors"
	"strings"
)

func ParseAuthBasicHeader(header string) (string, string, error) {
	var err error
	var username string
	var password string

	authData := strings.SplitN(header, " ", 2)
	if len(authData) < 2 {
		err = errors.New("Wrong authentification header")
		return username, password, err
	}
	authType := strings.TrimSpace(authData[0])
	if authType != "Basic" {
		err = errors.New("Authentification type is different from basic")
		return username, password, err
	}
	authPair := strings.TrimSpace(authData[1])

	pairEncoded, err := base64.StdEncoding.DecodeString(authPair)
	if err != nil {
		return username, password, err
	}
	pair := strings.SplitN(string(pairEncoded), ":", 2)
	if len(pair) < 2 {
		err = errors.New("Wrong authentification pair")
		return username, password, err
	}
	username = strings.TrimSpace(pair[0])
	password = strings.TrimSpace(pair[1])

	if username == "" {
		err = errors.New("autentification username is null")
		return username, password, err
	}
	if password == "" {
		err = errors.New("autentification password is null")
		return username, password, err
	}
	return username, password, err
}
