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) {
55 this.getLogger().trace(MessageFormat.format("application={0} - CALLED!", application)); //NOI18N
57 // Set application instance
58 this.setApplication(application);
60 // Init scanner instance
61 this.scanner = new Scanner(System.in);
64 this.getLogger().trace("EXIT!"); //NOI18N
68 * Displays a textual address "box" of given contact
70 * @param contact Contact to show address for
73 public void displayAddressBox (final Contact contact) {
75 this.getLogger().trace("contact=" + contact + " - CALLED!"); //NOI18N
78 if (contact == null) {
80 throw new NullPointerException("contact is null");
84 this.outputMessage(MessageFormat.format("Strasse, PLZ Ort, Land: {0}\n{1} {2}\n{3}", contact.getStreet(), contact.getZipCode(), contact.getCity(), contact.getCountryCode()));
87 this.getLogger().trace("EXIT!"); //NOI18N
91 * Displays a textual name "box" of given contact
93 * @param contact Contact to show name for
96 public void displayNameBox (final Contact contact) {
98 this.getLogger().trace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
101 if (contact == null) {
103 throw new NullPointerException("contact is null");
106 // Get translated gender as the user may want to see "Mr.", "Mrs."
107 String gender = contact.getTranslatedGender();
110 String companyName = contact.getCompanyName();
112 // If it is empty/null, then assume private contact
113 if ((companyName == null) || (companyName.isEmpty())) {
114 // Now put all together: gender, surname, family name
116 this.outputMessage(MessageFormat.format("Anrede, Vorname, Name: {0} {1} {2}", gender, contact.getSurname(), contact.getFamilyName()));
119 this.outputMessage(MessageFormat.format("Firma: {0}\nAnsprechpartner: {1} {2} {3}", companyName, gender, contact.getSurname(), contact.getFamilyName()));
123 this.getLogger().trace("EXIT!"); //NOI18N
127 * Displays a textual other data "box" of given contact
129 * @param contact Contact to show other data for
132 public void displayOtherDataBox (final Contact contact) {
134 this.getLogger().trace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
137 if (contact == null) {
139 throw new NullPointerException("contact is null");
142 // Cellphone and such ...
143 this.outputMessage(MessageFormat.format("Telefonnumer: {0}\nFaxnummer: {1}\nHandy: {2}\nKommentar:\n{3}", contact.getPhoneNumber(), contact.getFaxNumber(), contact.getCellphoneNumber(), contact.getComment()));
146 this.getLogger().trace("EXIT!"); //NOI18N
150 public void doChangeOwnAddressData (final Contact contact) {
152 this.getLogger().trace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
155 if (contact == null) {
157 throw new NullPointerException("contact is null");
160 // Make sure it is own contact
161 if (!contact.isOwnContact()) {
163 throw new IllegalArgumentException("Contact is not own data.");
167 String street = this.getContactManager().enterOwnStreet();
170 int zipCode = this.getContactManager().enterOwnZipCode();
173 String city = this.getContactManager().enterOwnCity();
176 String countryCode = this.getContactManager().enterOwnCountryCode();
178 // Update address data
179 contact.updateAddressData(street, zipCode, city, countryCode);
182 this.getLogger().trace("EXIT!"); //NOI18N
186 public void doChangeOwnNameData (final Contact contact) {
188 this.getLogger().trace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
191 if (contact == null) {
193 throw new NullPointerException("contact is null");
196 // Make sure it is own contact
197 if (!contact.isOwnContact()) {
199 throw new IllegalArgumentException("Contact is not own data.");
203 Gender gender = this.getContactManager().enterOwnGender();
206 String surname = this.getContactManager().enterOwnSurname();
209 String familyName = this.getContactManager().enterOwnFamilyName();
212 String companyName = this.getContactManager().enterOwnCompanyName();
214 // Update contact instance
215 contact.updateNameData(gender, surname, familyName, companyName);
218 this.getLogger().trace("EXIT!"); //NOI18N
222 public void doChangeOwnOtherData (final Contact contact) {
224 this.getLogger().trace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
227 if (contact == null) {
229 throw new NullPointerException("contact is null");
232 // Make sure it is own contact
233 if (!contact.isOwnContact()) {
235 throw new IllegalArgumentException("Contact is not own data.");
239 String phoneNumber = this.getContactManager().enterOwnPhoneNumber();
242 String cellNumber = this.getContactManager().enterOwnCellNumber();
245 String faxNumber = this.getContactManager().enterOwnFaxNumber();
248 String email = this.getContactManager().enterOwnEmailAddress();
251 String comment = this.getContactManager().enterOwnComment();
253 // Update contact instance
254 contact.updateOtherData(phoneNumber, cellNumber, faxNumber, email, null, comment);
257 this.getLogger().trace("EXIT!"); //NOI18N
261 public Contact doEnterOwnData () {
263 this.getLogger().trace("CALLED!"); //NOI18N
265 // First ask for gender
266 Gender gender = this.getContactManager().enterOwnGender();
269 String surname = this.getContactManager().enterOwnSurname();
271 // And 3rd for family name
272 String familyName = this.getContactManager().enterOwnFamilyName();
275 String companyName = this.getContactManager().enterOwnCompanyName();
277 // Construct UserContact instance
278 Contact contact = new UserContact(gender, surname, familyName, companyName);
281 this.getLogger().trace(MessageFormat.format("contact={0} - EXIT!", contact)); //NOI18N
288 * Shutdown this client
291 public void doShutdown () {
293 this.getLogger().trace("CALLED!"); //NOI18N
298 // @TODO Add other shutdown stuff
301 this.getLogger().trace("EXIT!"); //NOI18N
305 public void doUserMenuChoice () throws UnhandledUserChoiceException {
307 this.getLogger().trace("CALLED!"); //NOI18N
309 // Get all access keys from menu
310 char[] accessKeys = MenuTools.getAccessKeysFromMenuMap(this.getMenus(), this.getCurrentMenu());
312 // Output textural message and ask for a char as input
313 char choice = this.enterChar(accessKeys, "Bitte Auswahl eingeben (0=Programm beenden): ");
315 // @TODO Rewrite this ugly switch() block
317 case '1': // Enter/add own data
318 this.getContactManager().doEnterOwnData();
321 case '2': // Change own data
322 this.getContactManager().doChangeOwnData();
325 case '3': // Add new addess
326 this.getContactManager().doAddOtherAddress();
329 case '4': // List contacts
330 this.getContactManager().doListContacts();
333 case '5': // Search addresses
334 this.getContactManager().doSearchContacts();
337 case '6': // Change other addess
338 this.getContactManager().doChangeOtherAddress();
341 case '7': // Delete other address
342 this.getContactManager().doDeleteOtherAddress();
345 case '0': // Program exit
346 this.getApplication().doShutdown();
350 // @TODO throw own exception
351 throw new UnhandledUserChoiceException(MessageFormat.format("Choice '{0}' not handled yet.", choice));
355 this.getLogger().trace("EXIT!"); //NOI18N
359 * Asks the the user to enter a single character which must match validChars
361 * @param validChars Valid chars that are accepted
362 * @param message Message to user
363 * @return Allowed character
366 public char enterChar (final char[] validChars, final String message) {
368 this.getLogger().trace(MessageFormat.format("validChars={0},message={1} - CALLED!", Arrays.toString(validChars), message)); //NOI18N
370 // The validChars must not null be null and filled with at least one char
371 if (validChars == null) {
373 throw new NullPointerException("validChars is null");
374 } else if (validChars.length == 0) {
376 throw new IllegalArgumentException("validChars is not filled.");
381 // Sort array, else binarySearch() won't work
382 Arrays.sort(validChars);
384 // Keep asking until valid char has been entered
385 while (Arrays.binarySearch(validChars, input) < 0) {
387 System.out.print(message);
390 input = this.readChar();
394 this.getLogger().trace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
401 * Asks the user to enter his/her gender
403 * @param message Message to the user
404 * @return Gender enum
407 public Gender enterGender (final String message) {
409 this.getLogger().trace(MessageFormat.format("message={0} - CALLED!", message)); //NOI18N
412 char[] validChars = Gender.validChars();
415 //* NOISY-DEBUG: */ System.out.println(validChars);
417 char gender = this.enterChar(validChars, message);
419 // Now get a Gender instance back
420 Gender g = Gender.fromChar(gender);
422 // g must not be null
423 assert(g instanceof Gender) : "g is not set.";
426 this.getLogger().trace("g=" + g + " - EXIT!"); //NOI18N
433 * Reads an integer (int) with a textural message from the user
435 * @param minimum Minimum allowed number
436 * @param maximum Maximum allowed number
437 * @param message Messager to display in console
441 public int enterInt (final int minimum, final int maximum, final String message) {
443 this.getLogger().trace(MessageFormat.format("minimum={0},maximum={1},message={2} - CALLED!", minimum, maximum, message)); //NOI18N
445 // Minimum should not be below zero
446 assert (minimum >= 0);
447 assert (maximum > minimum);
452 while ((input < minimum) || (input > maximum)) {
454 System.out.print(message);
456 // Read integer from user
457 input = this.readInt();
461 this.getLogger().trace("input=" + input + " - EXIT!"); //NOI18N
468 * Reads a string of minimum and maximum length from the user
470 * @param minLength Minimum length of the string to read
471 * @param maxLength Maximum length of the string to read
472 * @param message Message to user
473 * @param allowEmpty Whether to allow empty string
474 * @return Entered string by user or null for empty strings
477 public String enterString (final int minLength, final int maxLength, final String message, final boolean allowEmpty) {
479 this.getLogger().trace(MessageFormat.format("minLength={0},maxLength={1},message={2}allowEmpty={3} - CALLED!", minLength, maxLength, message, allowEmpty)); //NOI18N
481 // Check on length, e.g. country codes are excactly 2 chars long
482 assert (maxLength >= minLength);
487 // Check if it is to short or to long
488 while (((input == null) || ((input.length() < minLength) && (!allowEmpty))) || ((input.length() > 0) && (input.length() < minLength) && (allowEmpty)) || ((input instanceof String) && (input.length() > maxLength))) {
490 System.out.print(message);
493 input = this.readString();
497 this.getLogger().trace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
504 * Returns a console menu item
506 * @param accessKey Key to access the menu
507 * @param text Text to show to user
508 * @return A SelectableMenuItem
509 * @todo Make sure the access key is unique
512 public SelectableMenuItem getMenuItem (final char accessKey, final String text) {
513 // Return a new console menu item
514 return new ConsoleMenuItem(accessKey, text);
518 * Inizializes this client
521 public void init () {
523 this.getLogger().trace("CALLED!"); //NOI18N
525 // Init contact manager here
526 this.initContactManager();
532 this.getLogger().trace("EXIT!"); //NOI18N
536 * Displays textural message to the user
541 public void outputMessage (final String message) {
542 System.out.println(message);
546 * Shows textural menu on console
549 public void showCurrentMenu () {
550 this.showMenu(this.getCurrentMenu());
554 * Shows given menu entry to user
556 * @param item Menu entry
559 public void showEntry (final SelectableMenuItem item) {
560 // Access key then text
561 this.outputMessage("[" + item.getAccessKey() + "] " + item.getText());
565 * Shows a textural message to the user
568 public void showWelcome () {
569 this.outputMessage(MessageFormat.format("Welcome to {0}", AddressbookApplication.printableTitle()));
570 this.outputMessage("");
571 this.outputMessage("Copyright(c) 2015 by Roland Haeder, this is free software");
574 this.getLogger().debug("Intro shown to user");
578 public void userChooseChangeContactData (final Contact contact) throws UnhandledUserChoiceException {
580 this.getLogger().trace(MessageFormat.format("contact={0} CALLED!", contact)); //NOI18N
582 // Contact must not be null
583 if (contact == null) {
585 throw new NullPointerException("contact is null");
588 // Ask the user for editing [name], [a]ddress or [other] data
589 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) ");
591 // @TODO Get rid of this ugly switch block, too
593 case 'n': // Name data
594 this.getContactManager().doChangeNameData(contact);
597 case 'a': // Address data
598 this.getContactManager().doChangeAddressData(contact);
601 case 'o': // Other data
602 this.getContactManager().doChangeOtherData(contact);
605 case 'x': // Exit this menu
606 // Ignored as it should go back
610 // @TODO throw own exception
611 throw new UnhandledUserChoiceException(MessageFormat.format("Choice '{0}' not handled yet.", choice));
615 this.getLogger().trace("EXIT!"); //NOI18N
619 * Reads one character
621 * @return A single character
623 private char readChar () {
625 String input = this.readString();
627 // This must be only one character
628 if (input.length() != 1) {
633 // Get char from first (and only) position
634 return input.charAt(0);
638 * Reads an integer (int) from user
640 * @return An integer number
642 private int readInt () {
643 // First read a string
644 String input = this.readString();
646 // Init number with invalid value
649 // Parse number, this can be risky
651 num = Integer.parseInt(input);
652 } catch (final NumberFormatException e) {
653 this.outputMessage("Bitte geben Sie nur Zahlen ein!");
654 this.getLogger().warn(MessageFormat.format("No numbers-only entered. input={0},message={1}", input, e.getMessage()));
657 // Return read number
662 * Reads a string from a scanner until RETURN is pressed
664 * @return Read string from scanner
666 private String readString () {
667 return this.scanner.nextLine();
671 * Fills menu map with menu entries
674 protected final void fillMenuMap () {
676 this.getLogger().trace("CALLED!"); //NOI18N
678 // Initialize first (main) menu
679 Menu menu = new ConsoleMenu("main", this);
682 this.getMenus().put("main", menu);
685 this.getLogger().trace("EXIT!"); //NOI18N