package com.jscape.inet.http.protocol.marshaling;

import com.jscape.util.Base64Format;

import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @author Alex Uzun
 */
public class BasicAuthorizationFormat {

    public static String format(String username, String password) {
        String credentialsData = Base64Format.formatData(String.format("%s:%s", username, password).getBytes(StandardCharsets.UTF_8));
        return String.format("Basic %s", credentialsData);
    }

    public static String format(Credentials credentials) {
        return format(credentials.username, credentials.password);
    }

    public static Credentials parse(String data)
            throws Exception {
        Scanner scanner = new Scanner(data).useDelimiter(" ");
        String authorizationType = scanner.next();

        if (!"Basic".equals(authorizationType)) {
            throw new Exception("Unsupported authorization type.");
        }

        String encodedCredentialsData = scanner.skip(" ").nextLine();
        String credentialsData = new String(Base64Format.parseData(encodedCredentialsData), StandardCharsets.UTF_8);
        Scanner credentialsScanner = new Scanner(credentialsData).useDelimiter(":");
        String username = credentialsScanner.next();
        String password = credentialsScanner.skip(":").nextLine();

        return new Credentials(username, password);
    }

    private BasicAuthorizationFormat() {
        // empty
    }

    public static class Credentials {

        public final String username;
        public final String password;

        public Credentials(String username, String password) {
            this.username = username;
            this.password = password;
        }
    }
}
