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.Gender;
28 import org.mxchange.addressbook.contact.user.UserContact;
29 import org.mxchange.addressbook.exceptions.UnhandledUserChoiceException;
30 import org.mxchange.addressbook.menu.Menu;
31 import org.mxchange.addressbook.menu.MenuTools;
32 import org.mxchange.addressbook.menu.console.ConsoleMenu;
33 import org.mxchange.addressbook.menu.item.SelectableMenuItem;
34 import org.mxchange.addressbook.menu.item.console.ConsoleMenuItem;
37 * A client for the console
39 * @author Roland Haeder
41 public class ConsoleClient extends BaseClient implements Client {
44 * Scanner instance for reading data from console input
46 private final Scanner scanner;
49 * Parameterless constructor
51 * @param application An instance of an Application class
53 public ConsoleClient (final Application application) {
56 // Set application instance
57 this.setApplication(application);
59 // Init scanner instance
60 this.scanner = new Scanner(System.in);
64 * Displays a textual address "box" of given contact
66 * @param contact Contact to show address for
69 public void displayAddressBox (final Contact contact) {
71 this.outputMessage(MessageFormat.format("Strasse, PLZ Ort, Land: {0}\n{1} {2}\n{3}", contact.getStreet(), contact.getZipCode(), contact.getCity(), contact.getCountryCode()));
75 * Displays a textual name "box" of given contact
77 * @param contact Contact to show name for
80 public void displayNameBox (final Contact contact) {
81 // Get translated gender as the user may want to see "Mr.", "Mrs."
82 String gender = contact.getTranslatedGender();
85 String companyName = contact.getCompanyName();
87 // If it is empty/null, then assume private contact
88 if ((companyName == null) || (companyName.isEmpty())) {
89 // Now put all together: gender, surname, family name
91 this.outputMessage(MessageFormat.format("Anrede, Vorname, Name: {0} {1} {2}", gender, contact.getSurname(), contact.getFamilyName()));
94 this.outputMessage(MessageFormat.format("Firma: {0}\nAnsprechpartner: {1} {2} {3}", companyName, gender, contact.getSurname(), contact.getFamilyName()));
99 * Displays a textual other data "box" of given contact
101 * @param contact Contact to show other data for
104 public void displayOtherDataBox (final Contact contact) {
105 // Cellphone and such ...
106 this.outputMessage(MessageFormat.format("Telefonnumer: {0}\nFaxnummer: {1}\nHandy: {2}\nKommentar:\n{3}", contact.getPhoneNumber(), contact.getFaxNumber(), contact.getCellphoneNumber(), contact.getComment()));
110 public void doChangeOwnAddressData (final Contact contact) {
111 // Make sure it is own contact
112 if (!contact.isOwnContact()) {
114 throw new IllegalArgumentException("Contact is not own data.");
118 String street = this.getContactManager().enterOwnStreet();
121 int zipCode = this.getContactManager().enterOwnZipCode();
124 String city = this.getContactManager().enterOwnCity();
127 String countryCode = this.getContactManager().enterOwnCountryCode();
129 // Update address data
130 contact.updateAddressData(street, zipCode, city, countryCode);
134 public void doChangeOwnNameData (final Contact contact) {
135 // Make sure it is own contact
136 if (!contact.isOwnContact()) {
138 throw new IllegalArgumentException("Contact is not own data.");
142 Gender gender = this.getContactManager().enterOwnGender();
145 String surname = this.getContactManager().enterOwnSurname();
148 String familyName = this.getContactManager().enterOwnFamilyName();
151 String companyName = this.getContactManager().enterOwnCompanyName();
153 // Update contact instance
154 contact.updateNameData(gender, surname, familyName, companyName);
158 public void doChangeOwnOtherData (final Contact contact) {
159 // Make sure it is own contact
160 if (!contact.isOwnContact()) {
162 throw new IllegalArgumentException("Contact is not own data.");
166 String phoneNumber = this.getContactManager().enterOwnPhoneNumber();
169 String cellNumber = this.getContactManager().enterOwnCellNumber();
172 String faxNumber = this.getContactManager().enterOwnFaxNumber();
175 String email = this.getContactManager().enterOwnEmailAddress();
178 String comment = this.getContactManager().enterOwnComment();
180 // Update contact instance
181 contact.updateOtherData(phoneNumber, cellNumber, faxNumber, email, null, comment);
185 public Contact doEnterOwnData () {
186 // First ask for gender
187 Gender gender = this.getContactManager().enterOwnGender();
190 String surname = this.getContactManager().enterOwnSurname();
192 // And 3rd for family name
193 String familyName = this.getContactManager().enterOwnFamilyName();
196 String companyName = this.getContactManager().enterOwnCompanyName();
198 // Construct UserContact instance
199 Contact contact = new UserContact(gender, surname, familyName, companyName);
206 * Shutdown this client
209 public void doShutdown () {
213 // @TODO Add other shutdown stuff
217 public void doUserMenuChoice () throws UnhandledUserChoiceException {
218 // Get all access keys from menu
219 char[] accessKeys = MenuTools.getAccessKeysFromMenuMap(this.getMenus(), this.getCurrentMenu());
221 // Output textural message and ask for a char as input
222 char choice = this.enterChar(accessKeys, "Bitte Auswahl eingeben (0=Programm beenden): ");
224 // @TODO Rewrite this ugly switch() block
226 case '1': // Enter/add own data
227 this.getContactManager().doEnterOwnData();
230 case '2': // Change own data
231 this.getContactManager().doChangeOwnData();
234 case '3': // Add new addess
235 this.getContactManager().doAddOtherAddress();
238 case '4': // List contacts
239 this.getContactManager().doListContacts();
242 case '5': // Search addresses
243 this.getContactManager().doSearchContacts();
246 case '6': // Change other addess
247 this.getContactManager().doChangeOtherAddress();
250 case '7': // Delete other address
251 this.getContactManager().doDeleteOtherAddress();
254 case '0': // Program exit
255 this.getApplication().doShutdown();
259 // @TODO throw own exception
260 throw new UnhandledUserChoiceException(MessageFormat.format("Choice '{0}' not handled yet.", choice));
265 * Asks the the user to enter a single character which must match validChars
267 * @param validChars Valid chars that are accepted
268 * @param message Message to user
269 * @return Allowed character
272 public char enterChar (final char[] validChars, final String message) {
275 // Sort array, else binarySearch() won't work
276 Arrays.sort(validChars);
278 // Keep asking until valid char has been entered
279 while (Arrays.binarySearch(validChars, input) < 0) {
281 System.out.print(message);
284 input = this.readChar();
292 * Asks the user to enter his/her gender
294 * @param message Message to the user
295 * @return Gender enum
298 public Gender enterGender (final String message) {
300 char[] validChars = Gender.validChars();
303 //* NOISY-DEBUG: */ System.out.println(validChars);
306 char gender = this.enterChar(validChars, message);
308 // Now get a Gender instance back
309 Gender g = Gender.fromChar(gender);
316 * Reads an integer (int) with a textural message from the user
318 * @param minimum Minimum allowed number
319 * @param maximum Maximum allowed number
320 * @param message Messager to display in console
324 public int enterInt (final int minimum, final int maximum, final String message) {
325 // Minimum should not be below zero
326 assert (minimum >= 0);
327 assert (maximum > minimum);
332 while ((input < minimum) || (input > maximum)) {
334 System.out.print(message);
336 // Read integer from user
337 input = this.readInt();
345 * Reads a string of minimum and maximum length from the user
347 * @param minLength Minimum length of the string to read
348 * @param maxLength Maximum length of the string to read
349 * @param message Message to user
350 * @param allowEmpty Whether to allow empty string
351 * @return Entered string by user or null for empty strings
354 public String enterString (final int minLength, final int maxLength, final String message, final boolean allowEmpty) {
355 // Check on length, e.g. country codes are excactly 2 chars long
356 assert (maxLength >= minLength);
361 // Check if it is to short or to long
362 while (((input == null) || ((input.length() < minLength) && (!allowEmpty))) || ((input.length() > 0) && (input.length() < minLength) && (allowEmpty)) || ((input instanceof String) && (input.length() > maxLength))) {
364 System.out.print(message);
367 input = this.readString();
375 * Returns a console menu item
377 * @param accessKey Key to access the menu
378 * @param text Text to show to user
379 * @return A SelectableMenuItem
380 * @todo Make sure the access key is unique
383 public SelectableMenuItem getMenuItem (final char accessKey, final String text) {
384 // Return a new console menu item
385 return new ConsoleMenuItem(accessKey, text);
389 * Inizializes this client
392 public void init () {
393 // Init contact manager here
394 this.initContactManager();
401 * Displays textural message to the user
406 public void outputMessage (final String message) {
407 System.out.println(message);
411 * Shows textural menu on console
414 public void showCurrentMenu () {
415 this.showMenu(this.getCurrentMenu());
419 * Shows given menu entry to user
421 * @param item Menu entry
424 public void showEntry (final SelectableMenuItem item) {
425 // Access key then text
426 this.outputMessage("[" + item.getAccessKey() + "] " + item.getText());
430 * Shows a textural message to the user
433 public void showWelcome () {
434 this.outputMessage(MessageFormat.format("Welcome to {0}", AddressbookApplication.printableTitle()));
435 this.outputMessage("");
436 this.outputMessage("Copyright(c) 2015 by Roland Haeder, this is free software");
439 this.getLogger().debug("Intro shown to user");
443 public void userChooseChangeContactData (final Contact contact) throws UnhandledUserChoiceException {
444 // Ask the user for editing [name], [a]ddress or [other] data
445 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) ");
447 // @TODO Get rid of this ugly switch block, too
449 case 'n': // Name data
450 this.getContactManager().doChangeNameData(contact, this);
453 case 'a': // Address data
454 this.getContactManager().doChangeAddressData(contact, this);
457 case 'o': // Other data
458 this.getContactManager().doChangeOtherData(contact, this);
461 case 'x': // Exit this menu
462 // Ignored as it should go back
466 // @TODO throw own exception
467 throw new UnhandledUserChoiceException(MessageFormat.format("Choice '{0}' not handled yet.", choice));
472 * Reads one character
474 * @return A single character
476 private char readChar () {
478 String input = this.scanner.nextLine();
480 // This must be only one character
481 if (input.length() != 1) {
486 // Get char from first (and only) position
487 return input.charAt(0);
491 * Reads an integer (int) from user
493 * @return An integer number
495 private int readInt () {
496 // First read a string
497 String input = this.readString();
499 // Init number with invalid value
502 // Parse number, this can be risky
504 num = Integer.parseInt(input);
505 } catch (final NumberFormatException e) {
506 this.outputMessage("Bitte geben Sie nur Zahlen ein!");
507 this.getLogger().warn(MessageFormat.format("No numbers-only entered. input={0},message={1}", input, e.getMessage()));
510 // Return read number
515 * Reads a string from a scanner until RETURN is pressed
517 * @return Read string from scanner
519 private String readString () {
520 return this.scanner.nextLine();
524 * Fills menu map with menu entries
527 protected final void fillMenuMap () {
528 // Initialize first (main) menu
529 Menu menu = new ConsoleMenu("main", this);
532 this.getMenus().put("main", menu);