package be.iminds.ilabt.jfed.experimenter_gui.slice;

import be.iminds.ilabt.jfed.highlevel.model.Slice;
import be.iminds.ilabt.jfed.lowlevel.GeniUserProvider;
import be.iminds.ilabt.jfed.rspec.model.BasicStringRspec;
import be.iminds.ilabt.jfed.rspec.model.javafx_impl.FXRspecNode;
import be.iminds.ilabt.jfed.ui.javafx.dialogs.JFDialogs;

import javax.annotation.Nonnull;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * User: twalcari
 * Date: 12/8/2014
 * Time: 14:00
 */
@Singleton
public class NodePropertiesDialogFactory {
    private final GeniUserProvider geniUserProvider;

    @Inject
    public NodePropertiesDialogFactory(GeniUserProvider geniUserProvider) {
        this.geniUserProvider = geniUserProvider;
    }


    public void showSimplePropertiesDialog(Slice slice, FXRspecNode node) {
        Optional<BasicStringRspec.LoginService> loginService = findLoginService(slice, node);
        if (loginService.isPresent()) {
            NodePropertiesDialog npd = new NodePropertiesDialog(slice, node, loginService.get());
            npd.showDialog();
        } else {
            JFDialogs.create()
                    .message("The selected node doesn't provide any information to perform an interactive login. Is this node ready?")
                    .masthead("No information available about this node")
                    .showWarning();
        }

    }


    private Optional<BasicStringRspec.LoginService> findLoginService(@Nonnull Slice slice, @Nonnull FXRspecNode node) {
        List<BasicStringRspec.LoginService> loginServices = slice.getManifestRspec().getNodeLoginInfo(node);

        if(loginServices == null)  {
            return Optional.empty();
        }

        //try to find a loginInfo with the username of the currently logged in user
        final String desiredUsername = geniUserProvider.getLoggedInGeniUser() != null &&
                geniUserProvider.getLoggedInGeniUser().getUserUrn() != null ?
                geniUserProvider.getLoggedInGeniUser().getUserUrn().getEncodedResourceName() : null;

        if (desiredUsername != null) {
            Optional<BasicStringRspec.LoginService> desiredLoginService =
                    loginServices.stream().filter(ls -> Objects.equals(desiredUsername, ls.getUsername())).findFirst();

            if (desiredLoginService.isPresent())
                return desiredLoginService;
        }

        //fallback: use the first loginService available
        return loginServices.stream().findFirst();
    }


}
