Commit 86ae3b0

Richard Luby <richluby@gmail.com>
2016-11-15 09:53:44
moved visual display logic
client display logic occurs through single channel in preparation for more in-depth ui experience
1 parent dcd65f0
client.go
@@ -1,11 +1,9 @@
 package main
 
 import (
-	"bufio"
 	"crypto/tls"
 	"crypto/x509"
 	"flag"
-	"fmt"
 	"github.com/BurntSushi/toml"
 	"io/ioutil"
 	"log"
@@ -48,42 +46,6 @@ func loadClientConfiguration(cfgFile string) CLIENT_CONFIG {
 	return clientConfig
 }
 
-// initUserSession starts the interactive prompt for the user
-func initUserSession() {
-	fmt.Printf("%s", "Welcome to the question interface. Use 'help' for more information.")
-	var input string
-	var command Command
-	var err error
-	reader := bufio.NewReader(os.Stdin)
-	for {
-		if clientConfig.USER == "" {
-			fmt.Print("\nUsername is blank. Setting to 'anonymous.' Use 'user' to change user name.")
-			clientConfig.USER = "anonymous"
-		}
-		fmt.Printf("\n:> ")
-		input, _ = reader.ReadString('\n')
-		args := strings.Fields(input)
-		if len(args) < 1 { // skip the empty strings
-			continue
-		}
-		// select a command from the list of available commands
-		if command, err = SelectCommand(strings.TrimSpace(args[0]), commandArray); err != nil {
-			log.Printf(COLOR_RED+"Error while parsing command: %+v"+COLOR_RESET, err)
-			continue
-		}
-		// parse the flags for the command
-		err = ParseUserCommands(args[1:], &command)
-		if err != nil {
-			log.Printf(COLOR_RED+"Error while parsing parameters: %+v"+COLOR_RESET, err)
-			continue
-		}
-		// execute the command and check for any errors that may have occurred
-		if err = command.Run(command); err != nil {
-			log.Printf(COLOR_RED+"Error while executing command: %+v"+COLOR_RESET, err)
-		}
-	}
-}
-
 // setupHttpClient initializes the http connection handler
 func setupHttpClient() {
 	ca_pool := x509.NewCertPool()
clientVisualization.go
@@ -0,0 +1,52 @@
+package main
+
+import (
+	"bufio"
+	"fmt"
+	"log"
+	"os"
+	"strings"
+)
+
+// displayStringToMainScreen prints the given string
+// to the primary string used by the application
+func displayStringToMainScreen(str string) {
+	fmt.Printf("%s", str)
+}
+
+// initUserSession starts the interactive prompt for the user
+func initUserSession() {
+	displayStringToMainScreen("Welcome to the question interface. Use 'help' for more information.")
+	if clientConfig.USER == "" {
+		displayStringToMainScreen("\nUsername is blank. Setting to 'anonymous.' Use 'user' to change user name.")
+		clientConfig.USER = "anonymous"
+	}
+	var input string
+	var command Command
+	var err error
+	reader := bufio.NewReader(os.Stdin)
+
+	for {
+		fmt.Printf("\n:> ")
+		input, _ = reader.ReadString('\n')
+		args := strings.Fields(input)
+		if len(args) < 1 { // skip the empty strings
+			continue
+		}
+		// select a command from the list of available commands
+		if command, err = SelectCommand(strings.TrimSpace(args[0]), commandArray); err != nil {
+			log.Printf(COLOR_RED+"Error while parsing command: %+v"+COLOR_RESET, err)
+			continue
+		}
+		// parse the flags for the command
+		err = ParseUserCommands(args[1:], &command)
+		if err != nil {
+			log.Printf(COLOR_RED+"Error while parsing parameters: %+v"+COLOR_RESET, err)
+			continue
+		}
+		// execute the command and check for any errors that may have occurred
+		if err = command.Run(command); err != nil {
+			log.Printf(COLOR_RED+"Error while executing command: %+v"+COLOR_RESET, err)
+		}
+	}
+}
command.go
@@ -19,7 +19,7 @@ import (
 var commandArray = []Command{Command{Command: "exit",
 	Description: "Exit the self-assessment application and close the connection.",
 	Run: func(command Command) error {
-		fmt.Print("Exiting application.\n")
+		displayStringToMainScreen("Exiting application.\n")
 		os.Exit(0)
 		return nil
 	}},
@@ -72,17 +72,25 @@ func displayHelp(command Command) error {
 			continue
 		}
 		if strings.Compare(checkCommand.Usage, "") == 0 { // print command help
-			fmt.Printf("> %s\n\t%s\n", COLOR_GREEN+checkCommand.Command+COLOR_RESET, checkCommand.Description)
+			displayStringToMainScreen(fmt.Sprintf("> %s\n\t%s\n",
+				COLOR_GREEN+checkCommand.Command+COLOR_RESET,
+				checkCommand.Description))
 		} else {
-			fmt.Printf("> %s\n\t%s\n", COLOR_GREEN+checkCommand.Usage+COLOR_RESET, checkCommand.Description)
+			displayStringToMainScreen(fmt.Sprintf("> %s\n\t%s\n",
+				COLOR_GREEN+checkCommand.Usage+COLOR_RESET,
+				checkCommand.Description))
 		}
 		if len(checkCommand.Flags) > 0 { // print flag help
-			fmt.Print(COLOR_BOLD + "\tFLAGS\n" + COLOR_RESET)
+			displayStringToMainScreen(COLOR_BOLD + "\tFLAGS\n" + COLOR_RESET)
 			for _, commandFlag := range checkCommand.Flags {
 				if commandFlag.Usage != "" {
-					fmt.Printf("\t%s\n\t\t%s\n", COLOR_BLUE+commandFlag.Usage+COLOR_RESET, commandFlag.Description)
+					displayStringToMainScreen(fmt.Sprintf("\t%s\n\t\t%s\n",
+						COLOR_BLUE+commandFlag.Usage+COLOR_RESET,
+						commandFlag.Description))
 				} else {
-					fmt.Printf("\t%s\n\t\t%s\n", COLOR_BLUE+commandFlag.Flag+COLOR_RESET, commandFlag.Description)
+					displayStringToMainScreen(fmt.Sprintf("\t%s\n\t\t%s\n",
+						COLOR_BLUE+commandFlag.Flag+COLOR_RESET,
+						commandFlag.Description))
 				}
 			}
 		}
@@ -98,38 +106,44 @@ func init() {
 // displayTests displays the previous tests to the user
 func displayTests(clientTests *[]ClientTest) {
 	hardRule := "--------------------------------------------------------"
-	fmt.Printf("\n%s\n%25s\n%s\n", hardRule, "Tests", hardRule)
-	fmt.Printf(" %3s | %7s | %9s | %3s | %7s | %9s |\n", "No.", "Score", "Questions",
-		"No.", "Score", "Questions")
-	fmt.Print(hardRule + "\n")
+	displayStringToMainScreen(fmt.Sprintf("\n%s\n%25s\n%s\n", hardRule, "Tests", hardRule))
+	displayStringToMainScreen(fmt.Sprintf(" %3s | %7s | %9s | %3s | %7s | %9s |\n",
+		"No.", "Score", "Questions",
+		"No.", "Score", "Questions"))
+	displayStringToMainScreen(hardRule + "\n")
 	numQuestions, numCorrect := float32(0.0), float32(0.0)
 	for i := 0; i < len(*clientTests); i++ {
 		numQ := float32(len((*clientTests)[i].Records))
-		fmt.Printf(" %3d |%7.2f%% | %9.0f |", i, (*clientTests)[i].Score, numQ)
+		displayStringToMainScreen(fmt.Sprintf(" %3d |%7.2f%% | %9.0f |", i,
+			(*clientTests)[i].Score, numQ))
 		numCorrect += (*clientTests)[i].Score / 100.0 * numQ
 		numQuestions += numQ
 		if i%2 != 0 && i != 0 {
-			fmt.Print("\n")
+			displayStringToMainScreen("\n")
 		}
 	}
-	fmt.Print("\n" + hardRule + "\n")
-	fmt.Printf("Average: %.2f%%\n%s\nQuestions Answered: %.0f\t Questions Correct: %.0f\n%s",
-		numCorrect/numQuestions*100, hardRule, numQuestions, numCorrect, hardRule)
+	displayStringToMainScreen("\n" + hardRule + "\n")
+	displayStringToMainScreen(fmt.Sprintf("Average: %.2f%%\n%s\nQuestions Answered: %.0f\t Questions Correct: %.0f\n%s",
+		numCorrect/numQuestions*100, hardRule, numQuestions, numCorrect, hardRule))
 }
 
 // displayTest displays a single test to the user
 func displayTest(clientTest ClientTest) {
-	fmt.Printf("Questions: %3d\nScore: %5.2f%%\n",
-		len(clientTest.Records), clientTest.Score)
+	displayStringToMainScreen(fmt.Sprintf("Questions: %3d\nScore: %5.2f%%\n",
+		len(clientTest.Records), clientTest.Score))
 	//	width, _, _ := terminal.GetSize(int(os.Stdin.Fd()))
 	for i, record := range clientTest.Records {
-		fmt.Printf("%2d) %s", i, record.Question)
+		displayStringToMainScreen(fmt.Sprintf("%2d) %s", i, record.Question))
 		answerLine := fmt.Sprintf("\nCorrect: %-25s Answer: %-25s",
 			COLOR_GREEN+record.Answer+COLOR_RESET, COLOR_RED+record.ClientAnswer+COLOR_RESET)
 		if record.AnsweredCorrectly {
-			fmt.Printf("%-40s%15s\n", answerLine, COLOR_GREEN+"[✓]"+COLOR_RESET)
+			displayStringToMainScreen(fmt.Sprintf("%-40s%15s\n",
+				answerLine,
+				COLOR_GREEN+"[✓]"+COLOR_RESET))
 		} else {
-			fmt.Printf("%-40s%15s\n", answerLine, COLOR_RED+"[X]"+COLOR_RESET)
+			displayStringToMainScreen(fmt.Sprintf("%-40s%15s\n",
+				answerLine,
+				COLOR_RED+"[X]"+COLOR_RESET))
 		}
 	}
 }
@@ -171,23 +185,25 @@ func runTest(clientTest *ClientTest) {
 	reader := bufio.NewReader(os.Stdin)
 	numCorrect := 0
 	for i, record := range clientTest.Records {
-		fmt.Printf("%d) [%s] %s\n", i+1, COLOR_BLUE+categoryKeys[record.Category]+COLOR_RESET,
-			record.Question)
+		displayStringToMainScreen(fmt.Sprintf("%d) [%s] %s\n", i+1,
+			COLOR_BLUE+categoryKeys[record.Category]+COLOR_RESET,
+			record.Question))
 		input, _ := reader.ReadString('\n')
 		input = strings.TrimSpace(input)
 		width, _, _ := terminal.GetSize(int(os.Stdin.Fd()))
 		if strings.Compare(input, record.Answer) == 0 {
 			// dynamically determine width of screen for right-alignment
-			fmt.Printf("%"+strconv.Itoa(width)+"s\n", COLOR_GREEN+"[✓]"+COLOR_RESET)
+			displayStringToMainScreen(fmt.Sprintf("%"+strconv.Itoa(width)+"s\n",
+				COLOR_GREEN+"[✓]"+COLOR_RESET))
 			clientTest.Records[i].AnsweredCorrectly = true
 			numCorrect++
 		} else if strings.Compare(input, "exit") == 0 {
 			clientTest.Score = calculateScore(numCorrect, len(clientTest.Records))
 			return
 		} else {
-			fmt.Printf("%s%"+strconv.Itoa(width-len(record.Answer)-5)+"s\n",
+			displayStringToMainScreen(fmt.Sprintf("%s%"+strconv.Itoa(width-len(record.Answer)-5)+"s\n",
 				COLOR_RED+record.Answer,
-				"[X]"+COLOR_RESET)
+				"[X]"+COLOR_RESET))
 			clientTest.Records[i].ClientAnswer = input
 		}
 	}
@@ -206,7 +222,7 @@ func postRecordsToServer(recordArray *ClientTest) error {
 	if resp.StatusCode != http.StatusCreated {
 		return fmt.Errorf("Error sending the results to the server: %s", response)
 	} else {
-		fmt.Print("\nTest submitted successfully.")
+		displayStringToMainScreen("\nTest submitted successfully.")
 	}
 	return err
 }
@@ -278,11 +294,13 @@ func buildBluePrint(useBlueprint bool) (string, error) {
 		return "", nil
 	}
 	var blueprint string
-	fmt.Print("Categories\n----------\n")
+	displayStringToMainScreen("Categories\n----------\n")
 	for i := 0; i < len(categoryKeys)-1; i += 2 {
-		fmt.Printf("%d) %-15s\t%d) %-15s\n", i, categoryKeys[i], i+1, categoryKeys[i+1])
+		displayStringToMainScreen(fmt.Sprintf("%d) %-15s\t%d) %-15s\n",
+			i, categoryKeys[i],
+			i+1, categoryKeys[i+1]))
 	}
-	fmt.Printf("Enter the category numbers, separated by a comma: ")
+	displayStringToMainScreen("Enter the category numbers, separated by a comma: ")
 	reader := bufio.NewReader(os.Stdin)
 	input, _ := reader.ReadString('\n')
 	splits := strings.Split(input, ",")
@@ -324,6 +342,6 @@ func executeTest(command Command) error {
 	clientTest.Username = clientConfig.USER
 
 	runTest(&clientTest)
-	fmt.Printf("You scored: %.2f%%.\n", clientTest.Score)
+	displayStringToMainScreen(fmt.Sprintf("You scored: %.2f%%.\n", clientTest.Score))
 	return postRecordsToServer(&clientTest)
 }