package com.workfusion.odf.core;

import java.util.Map;
import javax.inject.Named;

import groovy.lang.Binding;
import org.codejargon.feather.Provides;

import com.workfusion.bot.service.SecureEntryDTO;
import com.workfusion.odf.impl.connector.ShareFolderTransactionSupplier;
import com.workfusion.rpa.core.security.SecurityUtils;
import com.workfusion.rpa.core.storage.ShareFolderManager;

public class ShareFolderModule implements Module {
	/**
	 * Constructor.
	 */
    public ShareFolderModule() {
    	// nope
    }

    @Provides
    public ShareFolderManager shareFolderManager(Binding binding, @Named("botConfigParams") Map<String, String> params) {
        String alias = params.get(ShareFolderTransactionSupplier.PARAM_ALIAS);
        SecurityUtils securityUtils = new SecurityUtils(binding);
        SecureEntryDTO secureEntry = securityUtils.getSecureEntry(alias);
        String logonName = secureEntry.getKey();
        UserDTO user = parseLogonName(logonName);
        String password = secureEntry.getValue();

        return new ShareFolderManager(user.getDomain(), user.getUsername(), password);
    }

    /**
     * Parse user Down-Level Logon Name (https://docs.microsoft.com/en-us/windows/desktop/secauthn/user-name-formats).
     *
     * @param logonName Formatted as 'Username' or 'DOMAIN\Username'.
     * @return UserDTO file that contains domain (can be null) and user name.
     */
    private UserDTO parseLogonName(final String logonName) {
        String domain;
        String username;
        String[] userParts;
        if (logonName.contains("\\") && (userParts = logonName.split("\\\\")).length == 2) {
            domain = userParts[0];
            username = userParts[1];
        } else {
            domain = null;
            username = logonName;
        }

        return new UserDTO(username, domain);
    }

    /**
     * @author Andrei Urbanovich
     */
    final static class UserDTO {
        private final String username;
        private final String domain;

        public UserDTO(final String username, final String domain) {
            this.username = username;
            this.domain = domain;
        }

        public String getUsername() {
            return username;
        }

        public String getDomain() {
            return domain;
        }
    }
}
