package de.iteratec.karate.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;
import java.util.Optional;
import java.util.stream.Stream;

public class CredentialFileParser {
    Logger logger = LoggerFactory.getLogger(CredentialFileParser.class);
    public static BufferedReader bufferedReader; //keep this static to prevent garbage collection

    public Optional<Stream<Credentials>> loadFile(Path filePath){
        if(filePath == null){
            return Optional.empty();
        }

        try{
            bufferedReader = Files.newBufferedReader(filePath);
            return Optional.of(bufferedReader.lines()
                    .map(line -> extractCredentials(line, true))
                    .flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())
            );
        } catch (IOException e) {
            logger.error("failed to load credentials from file.",e);
            return Optional.empty();
        }
    }

    public Optional<Credentials> extractCredentials(String line, boolean isBase64Encoded){
        if(line != null && !line.isEmpty()) {
            String[] part = line.split(":");
            if (part.length != 2){
                return Optional.empty();
            }

            Credentials credentials = new Credentials();
            credentials.setUsername(part[0]);
            String password;
            if (isBase64Encoded) {
                password = new String(Base64.getDecoder().decode(part[1]));
            } else {
                password = part[1];
            }
            credentials.setPassword(password);
            return Optional.of(credentials);
        } else {
            return Optional.empty();
        }
    }
}