2 * Copyright (C) 2015 Roland Haeder
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 package org.mxchange.addressbook.client.console;
19 import java.text.MessageFormat;
20 import java.util.Arrays;
21 import java.util.Scanner;
22 import org.mxchange.addressbook.application.AddressbookApplication;
23 import org.mxchange.addressbook.application.Application;
24 import org.mxchange.addressbook.client.BaseClient;
25 import org.mxchange.addressbook.client.Client;
26 import org.mxchange.addressbook.contact.Contact;
27 import org.mxchange.addressbook.contact.user.UserContact;
28 import org.mxchange.addressbook.exceptions.UnhandledUserChoiceException;
29 import org.mxchange.addressbook.menu.Menu;
30 import org.mxchange.addressbook.menu.MenuTools;
31 import org.mxchange.addressbook.menu.console.ConsoleMenu;
32 import org.mxchange.addressbook.menu.item.SelectableMenuItem;
33 import org.mxchange.addressbook.menu.item.console.ConsoleMenuItem;
36 * A client for the console
38 * @author Roland Haeder
40 public class ConsoleClient extends BaseClient implements Client {
42 * Scanner instance for reading data from console input
44 private final Scanner scanner;
47 * Parameterless constructor
48 * @param application An instance of an Application class
50 public ConsoleClient (final Application application) {
53 // Set application instance
54 this.setApplication(application);
56 // Init scanner instance
57 this.scanner = new Scanner(System.in);
61 * Displays a textual address "box" of given contact
63 * @param contact Contact to show address for
66 public void displayAddressBox (final Contact contact) {
68 this.outputMessage(MessageFormat.format("Strasse, PLZ Ort, Land: {0}\n{1} {2}\n{3}", contact.getStreet(), contact.getZipCode(), contact.getCity(), contact.getCountryCode()));
72 * Displays a textual name "box" of given contact
74 * @param contact Contact to show name for
77 public void displayNameBox (final Contact contact) {
78 // Get translated gender as the user may want to see "Mr.", "Mrs."
79 String gender = contact.getTranslatedGender();
82 String companyName = contact.getCompanyName();
84 // If it is empty/null, then assume private contact
85 if ((companyName == null) || (companyName.isEmpty())) {
86 // Now put all together: gender, surname, family name
88 this.outputMessage(MessageFormat.format("Anrede, Vorname, Name: {0} {1} {2}", gender, contact.getSurname(), contact.getFamilyName()));
91 this.outputMessage(MessageFormat.format("Firma: {0}\nAnsprechpartner: {1} {2} {3}", companyName, gender, contact.getSurname(), contact.getFamilyName()));
96 * Displays a textual other data "box" of given contact
98 * @param contact Contact to show other data for
101 public void displayOtherDataBox (final Contact contact) {
102 // Cellphone and such ...
103 this.outputMessage(MessageFormat.format("Telefonnumer: {0}\nFaxnummer: {1}\nHandy: {2}\nKommentar:\n{3}", contact.getPhoneNumber(), contact.getFaxNumber(), contact.getCellphoneNumber(), contact.getComment()));
107 public void doChangeOwnAddressData (final Contact contact) {
108 // Make sure it is own contact
109 if (!contact.isOwnContact()) {
111 throw new IllegalArgumentException("Contact is not own data.");
115 String street = this.getContactManager().enterOwnStreet();
118 int zipCode = this.getContactManager().enterOwnZipCode();
121 String city = this.getContactManager().enterOwnCity();
124 String countryCode = this.getContactManager().enterOwnCountryCode();
126 // Update address data
127 contact.updateAddressData(street, zipCode, city, countryCode);
131 public void doChangeOwnNameData (final Contact contact) {
132 // Make sure it is own contact
133 if (!contact.isOwnContact()) {
135 throw new IllegalArgumentException("Contact is not own data.");
139 char gender = this.getContactManager().enterOwnGender();
142 String surname = this.getContactManager().enterOwnSurname();
145 String familyName = this.getContactManager().enterOwnFamilyName();
148 String companyName = this.getContactManager().enterOwnCompanyName();
150 // Update contact instance
151 contact.updateNameData(gender, surname, familyName, companyName);
155 public void doChangeOwnOtherData (final Contact contact) {
156 // Make sure it is own contact
157 if (!contact.isOwnContact()) {
159 throw new IllegalArgumentException("Contact is not own data.");
163 String phoneNumber = this.getContactManager().enterOwnPhoneNumber();
166 String cellNumber = this.getContactManager().enterOwnCellNumber();
169 String faxNumber = this.getContactManager().enterOwnFaxNumber();
172 String email = this.getContactManager().enterOwnEmailAddress();
175 String comment = this.getContactManager().enterOwnComment();
177 // Update contact instance
178 contact.updateOtherData(phoneNumber, cellNumber, faxNumber, email, null, comment);
182 public Contact doEnterOwnData () {
183 // First ask for gender
184 char gender = this.getContactManager().enterOwnGender();
187 String surname = this.getContactManager().enterOwnSurname();
189 // And 3rd for family name
190 String familyName = this.getContactManager().enterOwnFamilyName();
193 String companyName = this.getContactManager().enterOwnCompanyName();
195 // Construct UserContact instance
196 Contact contact = new UserContact(gender, surname, familyName, companyName);
203 * Shutdown this client
206 public void doShutdown () {
210 // @TODO Add other shutdown stuff
214 public void doUserMenuChoice () throws UnhandledUserChoiceException {
215 // Get all access keys from menu
216 char[] accessKeys = MenuTools.getAccessKeysFromMenuMap(this.getMenus(), this.getCurrentMenu());
218 // Output textural message and ask for a char as input
219 char choice = this.enterChar(accessKeys, "Bitte Auswahl eingeben (0=Programm beenden): ");
221 // @TODO Rewrite this ugly switch() block
223 case '1': // Enter/add own data
224 this.getContactManager().doEnterOwnData();
227 case '2': // Change own data
228 this.getContactManager().doChangeOwnData();
231 case '3': // Add new addess
232 this.getContactManager().doAddOtherAddress();
235 case '4': // List contacts
236 this.getContactManager().doListContacts();
239 case '5': // Search addresses
240 this.getContactManager().doSearchContacts();
243 case '6': // Change other addess
244 this.getContactManager().doChangeOtherAddress();
247 case '7': // Delete other address
248 this.getContactManager().doDeleteOtherAddress();
251 case '0': // Program exit
252 this.getApplication().doShutdown();
256 // @TODO throw own exception
257 throw new UnhandledUserChoiceException(MessageFormat.format("Choice '{0}' not handled yet.", choice));
262 * Asks the the user to enter a single character which must match validChars
263 * @param validChars Valid chars that are accepted
264 * @param message Message to user
265 * @return Allowed character
268 public char enterChar (final char[] validChars, final String message) {
271 // Sort array, else binarySearch() won't work
272 Arrays.sort(validChars);
274 // Keep asking until valid char has been entered
275 while (Arrays.binarySearch(validChars, input) < 0) {
277 System.out.print(message);
280 input = this.readChar();
288 * Reads an integer (int) with a textural message from the user
290 * @param minimum Minimum allowed number
291 * @param maximum Maximum allowed number
292 * @param message Messager to display in console
296 public int enterInt (final int minimum, final int maximum, final String message) {
297 // Minimum should not be below zero
298 assert(minimum >= 0);
299 assert(maximum > minimum);
304 while ((input < minimum) || (input > maximum)) {
306 System.out.print(message);
308 // Read integer from user
309 input = this.readInt();
317 * Reads a string of minimum and maximum length from the user
319 * @param minLength Minimum length of the string to read
320 * @param maxLength Maximum length of the string to read
321 * @param message Message to user
322 * @param allowEmpty Whether to allow empty string
323 * @return Entered string by user or null for empty strings
326 public String enterString (final int minLength, final int maxLength, final String message, final boolean allowEmpty) {
327 // Check on length, e.g. country codes are excactly 2 chars long
328 assert(maxLength >= minLength);
333 // Check if it is to short or to long
334 while (((input == null) || ((input.length() < minLength) && (!allowEmpty))) || ((input.length() > 0) && (input.length() < minLength) && (allowEmpty)) || ((input instanceof String) && (input.length() > maxLength))) {
336 System.out.print(message);
339 input = this.readString();
347 * Returns a console menu item
349 * @param accessKey Key to access the menu
350 * @param text Text to show to user
351 * @return A SelectableMenuItem
352 * @todo Make sure the access key is unique
355 public SelectableMenuItem getMenuItem (final char accessKey, final String text) {
356 // Return a new console menu item
357 return new ConsoleMenuItem(accessKey,text);
361 * Inizializes this client
364 public void init () {
365 // Init contact manager here
366 this.initContactManager();
373 * Displays textural message to the user
377 public void outputMessage (final String message) {
378 System.out.println(message);
382 * Shows textural menu on console
385 public void showCurrentMenu () {
386 this.showMenu(this.getCurrentMenu());
390 * Shows given menu entry to user
392 * @param item Menu entry
395 public void showEntry (final SelectableMenuItem item) {
396 // Access key then text
397 this.outputMessage("[" + item.getAccessKey() + "] " + item.getText());
401 * Shows a textural message to the user
404 public void showWelcome () {
405 this.outputMessage(MessageFormat.format("Welcome to {0}", AddressbookApplication.printableTitle()));
406 this.outputMessage("");
407 this.outputMessage("Copyright(c) 2015 by Roland Haeder, this is free software");
410 this.getLogger().debug("Intro shown to user");
414 public void userChooseChangeContactData (final Contact contact) throws UnhandledUserChoiceException {
415 // Ask the user for editing [name], [a]ddress or [other] data
416 char choice = this.enterChar(new char[]{'n', 'a', 'o', 'x'}, "Welchen Daten möchten Sie ändern? (n=Namensdaten, a=Anschriftsdaten, o=Andere, x=Zurück zur Hauptauswahl) ");
418 // @TODO Get rid of this ugly switch block, too
420 case 'n': // Name data
421 this.getContactManager().doChangeNameData(contact, this);
424 case 'a': // Address data
425 this.getContactManager().doChangeAddressData(contact, this);
428 case 'o': // Other data
429 this.getContactManager().doChangeOtherData(contact, this);
432 case 'x': // Exit this menu
433 // Ignored as it should go back
437 // @TODO throw own exception
438 throw new UnhandledUserChoiceException(MessageFormat.format("Choice '{0}' not handled yet.", choice));
443 * Reads one character
445 * @return A single character
447 private char readChar () {
449 String input = this.scanner.nextLine();
451 // This must be only one character
452 if (input.length() != 1) {
457 // Get char from first (and only) position
458 return input.charAt(0);
462 * Reads an integer (int) from user
464 * @return An integer number
466 private int readInt () {
467 // First read a string
468 String input = this.readString();
470 // Init number with invalid value
473 // Parse number, this can be risky
475 num = Integer.parseInt(input);
476 } catch (final NumberFormatException e) {
477 this.outputMessage("Bitte geben Sie nur Zahlen ein!");
478 this.getLogger().warn(MessageFormat.format("No numbers-only entered. input={0},message={1}", input, e.getMessage()));
481 // Return read number
486 * Reads a string from a scanner until RETURN is pressed
488 * @return Read string from scanner
490 private String readString () {
491 return this.scanner.nextLine();
495 * Fills menu map with menu entries
498 protected final void fillMenuMap () {
499 // Initialize first (main) menu
500 Menu menu = new ConsoleMenu("main", this);
503 this.getMenus().put("main", menu);