summaryrefslogtreecommitdiffstats
path: root/EssentialsUpdate/src/com/earth2me/essentials/update/states/StateMachine.java
blob: 53612715eca73d48d6c7330a4e3defe6fd3c9b11 (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
112
113
114
115
package com.earth2me.essentials.update.states;

import com.earth2me.essentials.update.WorkListener;
import com.earth2me.essentials.update.VersionInfo;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;


public class StateMachine extends WorkListener
{
	public enum MachineResult
	{
		ABORT, WAIT, DONE
	}
	private final transient StateMap states = new StateMap();
	private transient AbstractState current;
	private final transient Player player;

	public StateMachine(final Plugin plugin, final Player player, final VersionInfo newVersionInfo)
	{
		super(plugin, newVersionInfo);
		this.player = player;
		states.clear();
		states.put(EssentialsChat.class, new EssentialsChat(states));
		current = states.get(0);
	}

	public MachineResult askQuestion()
	{
		while (current.guessAnswer())
		{
			current = current.getNextState();
			if (current == null)
			{
				return MachineResult.DONE;
			}
		}
		current.askQuestion(player);
		return MachineResult.WAIT;
	}

	public MachineResult reactOnMessage(final String message)
	{
		final AbstractState next = current.reactOnAnswer(player, message);
		if (next == null)
		{
			if (current.isAbortion())
			{
				return MachineResult.ABORT;
			}
			else
			{
				return MachineResult.DONE;
			}
		}
		current = next;
		return askQuestion();
	}
	private int position = 0;

	public void startWork()
	{
		callStateWork();
	}

	private void callStateWork()
	{
		if (position > states.size())
		{
			if (player.isOnline())
			{
				player.sendMessage("Installation done.");
			}
			return;
		}
		final AbstractState state = states.get(position);
		state.doWork(this);
	}

	@Override
	public void onWorkAbort(final String message)
	{
		position = 0;
		Bukkit.getScheduler().scheduleSyncDelayedTask(getPlugin(), new Runnable()
		{
			@Override
			public void run()
			{
				if (message != null && !message.isEmpty() && StateMachine.this.player.isOnline())
				{
					StateMachine.this.player.sendMessage(message);
				}
			}
		});
	}

	@Override
	public void onWorkDone(final String message)
	{
		position++;
		Bukkit.getScheduler().scheduleSyncDelayedTask(getPlugin(), new Runnable()
		{
			@Override
			public void run()
			{
				if (message != null && !message.isEmpty() && StateMachine.this.player.isOnline())
				{
					StateMachine.this.player.sendMessage(message);
				}
				StateMachine.this.callStateWork();
			}
		});
	}
}