summaryrefslogtreecommitdiffstats
path: root/EssentialsUpdate/src/com/earth2me/essentials/update/states/AbstractState.java
blob: 6d2613a4005ac06449ea6d365d333620744c6b79 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package com.earth2me.essentials.update.states;

import com.earth2me.essentials.update.WorkListener;
import org.bukkit.entity.Player;


public abstract class AbstractState
{
	private transient boolean abortion = false;
	private final transient StateMap stateMap;
	
	public AbstractState(final StateMap stateMap)
	{
		this.stateMap = stateMap;
	}
	
	public <T extends AbstractState> T getState(final Class<? extends T> stateClass)
	{
		if (!stateMap.containsKey(stateClass))
		{
			try
			{
				final AbstractState state = stateClass.getConstructor(StateMap.class).newInstance(stateMap);
				stateMap.put(stateClass, state);
			}
			catch (Exception ex)
			{
				/*
				 * This should never happen.
				 * All states that are added to the map automatically,
				 * have to have a Constructor that accepts the StateMap.
				 */
				throw new RuntimeException(ex);
			}
		}
		return (T)stateMap.get(stateClass);
	}
	
	public abstract AbstractState getNextState();

	/**
	 * Check if we already know the answer, so the user does not have to answer the question.
	 * 
	 * @return true, if the answer could be guessed.
	 */
	public boolean guessAnswer()
	{
		return false;
	}

	/**
	 * Ask the user the question.
	 * @param sender 
	 */
	public abstract void askQuestion(Player sender);

	/**
	 * React on the answer and set internal variables
	 * @param answer
	 * @return true, if the answer could be recognized as a valid answer
	 */
	public abstract boolean reactOnAnswer(String answer);
	
	public final AbstractState reactOnAnswer(final Player sender, final String answer)
	{
		final String trimmedAnswer = answer.trim();
		if (trimmedAnswer.equalsIgnoreCase("quit")
			|| trimmedAnswer.equalsIgnoreCase("bye")
			|| trimmedAnswer.equalsIgnoreCase("abort"))
		{
			abort();
			return null;
		}
		try
		{
			final boolean found = reactOnAnswer(trimmedAnswer);
			if (found)
			{
				return getNextState();
			}
			else
			{
				sender.sendMessage("Answer not recognized.");
				return this;
			}
		}
		catch (RuntimeException ex)
		{
			sender.sendMessage(ex.toString());
			return this;
		}	
	}

	/**
	 * Do something based on the answer, that the user gave.
	 */
	public void doWork(final WorkListener listener)
	{
		listener.onWorkDone();
	}
	
	public boolean isAbortion()
	{
		return abortion;
	}
	
	protected void abort()
	{
		abortion = true;
	}
}