package com.sequenceiq.redbeams.service;

import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.sequenceiq.cloudbreak.cloud.azure.view.AzureDatabaseServerView;
import com.sequenceiq.cloudbreak.cloud.model.DatabaseServer;
import com.sequenceiq.cloudbreak.common.mappable.CloudPlatform;
import com.sequenceiq.cloudbreak.util.PasswordUtil;
import com.sequenceiq.common.model.AzureDatabaseType;

@Service
public class UserGeneratorService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserGeneratorService.class);

    private static final int USER_NAME_LENGTH = 10;

    public String generateUserName() {
        return PasswordUtil.getRandomAlphabeticWithLowerCaseOnly(USER_NAME_LENGTH);
    }

    /**
     * Updates an original username based on additional information available
     * after allocation. Updates depend on the cloud platform, and since some
     * platforms do not require updates, this method may return the original
     * username without updates.
     *
     * @param databaseServer   information about the database server
     * @param originalUserName original username (generated by this service, nominally)
     * @param cloudPlatform    cloud provider whose rules must be followed, if known
     * @param dbHostname       database server hostname
     * @return updated username
     */
    public String updateUserName(DatabaseServer databaseServer, String originalUserName, Optional<CloudPlatform> cloudPlatform, String dbHostname) {
        if (cloudPlatform.isEmpty()) {
            return originalUserName;
        }

        String updatedUserName;
        if (cloudPlatform.get() == CloudPlatform.AZURE) {
            AzureDatabaseServerView azureDatabaseServerView = new AzureDatabaseServerView(databaseServer);
            if (azureDatabaseServerView.getAzureDatabaseType() == AzureDatabaseType.SINGLE_SERVER) {
                String dbShortHostname = dbHostname.split("\\.")[0];
                updatedUserName = originalUserName + "@" + dbShortHostname;
                LOGGER.debug("Updating username for Azure Single DB Server to {}", updatedUserName);
            } else {
                updatedUserName = originalUserName;
                LOGGER.debug("No need to extend the username for Azure Flexible DB Server with the hostname, username is {}", updatedUserName);
            }
        } else {
            updatedUserName = originalUserName;
            LOGGER.debug("No need to change the username of the DB Server on {} cloudplatform, username is {}", cloudPlatform.get(), updatedUserName);
        }

        return updatedUserName;
    }
}
