package org.codehaus.plexus.components.interactivity;

/*
 * The MIT License
 *
 * Copyright (c) 2005, The Codehaus
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is furnished to do
 * so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

import javax.inject.Inject;
import javax.inject.Named;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

/**
 * Default prompter.
 *
 * @author Brett Porter
 */
@Named
public class DefaultPrompter implements Prompter {
    private final OutputHandler outputHandler;

    private final InputHandler inputHandler;

    @Inject
    public DefaultPrompter(OutputHandler outputHandler, InputHandler inputHandler) {
        this.outputHandler = outputHandler;
        this.inputHandler = inputHandler;
    }

    @Override
    public String prompt(String message) throws PrompterException {
        try {
            writePrompt(message);
        } catch (IOException e) {
            throw new PrompterException("Failed to present prompt", e);
        }

        try {
            return inputHandler.readLine();
        } catch (IOException e) {
            throw new PrompterException("Failed to read user response", e);
        }
    }

    @Override
    public String prompt(String message, String defaultReply) throws PrompterException {
        try {
            writePrompt(formatMessage(message, null, defaultReply));
        } catch (IOException e) {
            throw new PrompterException("Failed to present prompt", e);
        }

        try {
            String line = inputHandler.readLine();
            if (line == null || line.isEmpty()) {
                line = defaultReply;
            }
            return line;
        } catch (IOException e) {
            throw new PrompterException("Failed to read user response", e);
        }
    }

    @Override
    public String prompt(String message, List<String> possibleValues, String defaultReply) throws PrompterException {
        String formattedMessage = formatMessage(message, possibleValues, defaultReply);

        String line;

        do {
            try {
                writePrompt(formattedMessage);
            } catch (IOException e) {
                throw new PrompterException("Failed to present prompt", e);
            }

            try {
                line = inputHandler.readLine();
                if (line == null && defaultReply == null) {
                    throw new IOException("EOF");
                }
            } catch (IOException e) {
                throw new PrompterException("Failed to read user response", e);
            }

            if (line == null || line.isEmpty()) {
                line = defaultReply;
            }

            if (line != null && !possibleValues.contains(line)) {
                try {
                    outputHandler.writeLine("Invalid selection.");
                } catch (IOException e) {
                    throw new PrompterException("Failed to present feedback", e);
                }
            }
        } while (line == null || !possibleValues.contains(line));

        return line;
    }

    @Override
    public String prompt(String message, List<String> possibleValues) throws PrompterException {
        return prompt(message, possibleValues, null);
    }

    @Override
    public String promptForPassword(String message) throws PrompterException {
        try {
            writePrompt(message);
        } catch (IOException e) {
            throw new PrompterException("Failed to present prompt", e);
        }

        try {
            return inputHandler.readPassword();
        } catch (IOException e) {
            throw new PrompterException("Failed to read user response", e);
        }
    }

    private String formatMessage(String message, List<String> possibleValues, String defaultReply) {
        StringBuilder formatted = new StringBuilder(message.length() * 2);

        formatted.append(message);

        if (possibleValues != null && !possibleValues.isEmpty()) {
            formatted.append(" (");

            for (Iterator<String> it = possibleValues.iterator(); it.hasNext(); ) {
                String possibleValue = it.next();

                formatted.append(possibleValue);

                if (it.hasNext()) {
                    formatted.append('/');
                }
            }

            formatted.append(')');
        }

        if (defaultReply != null) {
            formatted.append(' ').append(defaultReply);
        }

        return formatted.toString();
    }

    private void writePrompt(String message) throws IOException {
        outputHandler.write(message + ": ");
    }

    @Override
    public void showMessage(String message) throws PrompterException {
        try {
            writePrompt(message);
        } catch (IOException e) {
            throw new PrompterException("Failed to present prompt", e);
        }
    }
}
