/*
 * help.c
 *
 *  Created on: Mar 25, 2022
 *      Author: thomm
 */

#include <stdio.h>
#include <stdlib.h>

#include "system.h"
#include "help.h"
#include "config.h"
#include "user_io.h"
#include "uartstdio.h"

extern int dbg_flag;        // defd in main.c
const char* wisdom_arr[];

void print_help_menu(void)
{
    uprintf("\r\n\r\n\r\nHelp Menu\r\n");
    uprintf("C -- Configuration help\r\n");
    uprintf("T -- Test help\r\n");
    uprintf("D -- Deployment help\r\n");
    uprintf("P -- pH and DuraFET Voltage Wisdom\r\n");
    uprintf("S -- Sampling info\r\n");
    if(sys_data.app_cfg[APPCFG_MENU_LEVEL] == 1) uprintf("\r\n");
    if(sys_data.app_cfg[APPCFG_MENU_LEVEL] == 1) uprintf("M/m -MicroSD Logging Enable / disable\r\n");
    if(sys_data.app_cfg[APPCFG_MENU_LEVEL] == 1) uprintf("Q/q -Advanced menus Enable / disable\r\n");
    //uprintf("Q/q -Advanced menus Enable / disable\r\n");
    if(sys_data.app_cfg[APPCFG_MENU_LEVEL] == 1) uprintf("Z/z -dbg_printf statements Enable / disable\r\n");
    uprintf("\r\n");
    uprintf("9 -- Exit to Main Menu\r\n");
    uprintf("\r\nEnter Selection [9]: ");

}

void help_menu(void)
{

    char input;
    uint32_t indx, indx2, indx3;
    int iTemp;
    time_t timer;


    uprintf("\r\n\r\nVersion -- %s, %s \r\n ", VERSION, NONVOLATILEMEM);      // VERSION is defd in system.h
#if BOARD_MFET >= 1 
    //uprintf("\r\nMFET Power Consumption per Sample with min data config = ~0.2 Joules per sample:  12v, 1.2sec, ~14.5mA => 12 * 14.5 * (1.2 / 3600) * 3.6 = ~0.2 Joules\r\n\r\n");
#endif
#if BOARD_MPHOX == 1  || BOARD_MSC == 1
    //uprintf("\r\nMPHOX Power Consumption per Sample with min data config = ~0.2 Joules per sample:  12v, 1.8sec, ~14.5mA => 12 * 14.5 * (1.8 / 3600) * 3.6 = ~0.3 Joules\r\n\r\n");
#endif
#if BOARD_NANOFET >= 1
    //uprintf("\r\nNANOFET Power Consumption per Sample = TBD\r\n\r\n");
#endif

    // Test menu loop
    while(1)
    {
        print_help_menu();

        UARTFlushRx();
        timer = 30000 + ROM_HibernateRTCGet();

        while(1)
        {
            if( UARTRxBytesAvail() )
            {
                input = get_key();
                break;
            }

            if( timer <= ROM_HibernateRTCGet() ) sleep(IDLE, 0);
        }

        switch(input)
        {
        case 'b':
            uprintf("\r\n\r\n\r\n");
            uprintf("      \\|/(_)_(_)\\|/\r\n");
            uprintf("       @~ (o.o) ~@\r\n");
            uprintf("      /___( * )___\\   NA NA\r\n");
            uprintf("         / `U' \\      NANA\r\n");
            uprintf("        (   .   )      NA !!!\r\n");
            uprintf("         `>---<'    You Cant Get Me...\r\n");
            uprintf("         _\\   /_     Bug Hunt!!!\r\n");
            uprintf("\r\n\r\n\r\n");
            break;

        case 'c':
        case 'C':
            uprintf("\r\n\r\n--------- Configuration --------------\r\n");
            uprintf("Configuration checklist: (use Main Menu 1--Configure)\r\n");
            uprintf("1 -- Set Clock\r\n");
            uprintf("2 -- Change File Name\r\n");
            uprintf("3 -- Set Deployment Parameters\r\n");
            uprintf("        - Sample aligned to hour? (Y/N) [Y]?\r\n");
            uprintf("        - Enter sample period [20] sec:   Polled Mode: configure with a period of 0 seconds\r\n");
            //uprintf("\r\n       Enter pH sample average [5] samples:");
            uprintf("        - Enter pump on time [0] sec:\r\n");
            uprintf("        - Enter low battery_voltage (10.5 V for MpHOx with pump, 5.5 V for MFET) [5.5 V]:\r\n");
            uprintf("4 -- Enter pH Sensor Calibration Coefficients\r\n");
            uprintf("7 -- Config Data Fields\r\n");
            uprintf("        - Upper case letter to enable data field, Lower case letter to disable\r\n");
            uprintf("        - 4 -- Use Case: MpHOx Default,  MicroSD logging is enabled, Console echo is enabled\r\n");
            uprintf("        - 5 -- Use Case: MpHOx m2m,    MicroSD logging is disabled, Console echo is disabled\r\n");
            uprintf("\r\n\r\n");
            uprintf("Optional config settings\r\n");
            uprintf("A -- App Config Fields     For disabling MicroSD logging, or suppressing character echo for machine-to-machine\r\n");
            uprintf("E -- Edit/Copy EEPROM sys_data structure     Run this after firmware upgrade to insure settings are correctly copied\r\n");
            uprintf("\r\n\r\n");
            wait_consoleTx();
            break;

        case 'h':
            print_help_menu();
            break;
        case 'H':
            uprintf("\r\n\r\n");
            srand((unsigned) ROM_HibernateRTCGet());
            while(1)
            {
                // generate number 0 to 61
                indx = rand() % 62;  // todo, how to get the number of strings in wisdom_arr
                indx2 = strlen((char *)wisdom_arr[indx]);
                indx2 /= 15;
                //uprintf("%06u: %s\r", (8000 + (indx2*2000)), wisdom_arr[indx]);
                uprintf("  %s\r\n", wisdom_arr[indx]);

                iTemp = getchar_timed((int)(8 + (indx2*2)) );
                //ROM_SysCtlDelay(MILLISECOND * (8000 + (indx2*2000)) );
                uprintf("                                                                                                                                                                                                                     \r");

                wait_consoleTx();
                if(iTemp > 0 && iTemp != 'n')
                {
                     break;
                }

            }
            print_help_menu();
            break;

        case 'm':
            if(sys_data.app_cfg[APPCFG_MENU_LEVEL] == 1)
            {
                sys_data.app_cfg[APPCFG_MICROSD_ENABLE] = 0;
                uprintf("MicroSD card DISabled, no Logging\r\n\r\n");
                storeSysDataVariables();
            }
            break;
        case 'M':
            if(sys_data.app_cfg[APPCFG_MENU_LEVEL] == 1)
            {
                sys_data.app_cfg[APPCFG_MICROSD_ENABLE] = 1;
                uprintf("MicroSD card Enabled for Logging\r\n\r\n");
                storeSysDataVariables();
            }
            break;

        case 't':
        case 'T':
            uprintf("\r\n\r\n--------- Test Mode commands ---------\r\n");
            uprintf("Test menu: (use Main Menu 3--Test)\r\n");
            uprintf("\r\n");
            uprintf("Run QA and setup after board manufacture to initialize EEPROM and configuration defaults - CLEARS EEPROM MetaData and config, restores defaults\r\n");
            uprintf("\r\n");
            uprintf("For 24bit ADC and Analog board bringup, use 8 -- Test 24bit ADC and MUX channels\r\n");
            uprintf("\r\n");
            uprintf("Use d -- Data Header to see the data fields configured for logging as well as sampling sequence timing, Use D for continuous sampling\r\n");
            uprintf("\r\n");
            uprintf("Test communications with periperhal instruments such as Aanderaa optode, conductivity, SBE37 MicroCat CTD\r\n");
            //uprintf("    1 -- Battery and Board Sensors\r\n");
            //uprintf("    2 -- Durafet voltages\r\n");
            //uprintf("    3 -- Calc pH using Int Ref and Thermistor\r\n");
            //uprintf("    4 -- Calc pH using Ext Ref, Thermistor and Salinity\r\n");
            //uprintf("    5 -- Communicate with Instrument\r\n");
            //uprintf("    6 -- Power Output Tests for AUXx and Pump\r\n");
            //uprintf("    8 -- Test 24bit ADC and MUX channels\r\n");
            //uprintf("    D -- Data Header print and test\r\n");
            //uprintf("    M -- MetaData print\r\n");
            //uprintf("    Q -- QA and setup after board manufacture\r\n");
            uprintf("\r\n\r\n");
            wait_consoleTx();
            break;
        case 'd':
        case 'D':
            uprintf("\r\n\r\n------ Deployment Mode commands ------\r\n");
            uprintf("any character to wake, then issue command:\r\n");
            uprintf("stop  -- stop sampling, exit deployment mode\r\n");
            //uprintf("gdata -- get data since last command\r\n");
            uprintf("ts    -- take sample\r\n");
            uprintf("ss    -- start sample followed by 'sl' command to send last sample, times out after 8 sec\r\n");
            uprintf("gh    -- get data header\r\n");
            uprintf("gm    -- get metadata\r\n");
            uprintf("Ctrl-X, then <Enter> during sampling pump cycle to end pump cycle\r\n");
            uprintf("\r\n\r\n");
            wait_consoleTx();
            break;
        case 'p':
        case 'P':
            uprintf("\r\n\r\n------ pH and DuraFET Voltage Wisdom ------\r\n");
            uprintf("\r\nVtherm:        ~1.1V at 20C");
            uprintf("\r\nVrsi:          Internal reference based pH in seawater: ~-0.9V. In original buffer solution: ~-1.1V");
            uprintf("\r\nVrsi_B:        Electrical bias on ISFET voltage so that 7pH is 0V with respect to internal reference");
            uprintf("\r\n                  Then it changes by approximately 60 mV / pH.");
            uprintf("\r\n                  So nominal seawater (pH~=8), VrsiBiased ~= 60mV ± 30 mV");
            uprintf("\r\nVrsi std:      Standard deviation should be < 50uV, typical is ~20uV");
            uprintf("\r\nVrse:          External reference based pH in seawater (DeepSea Durafet only) ");
            //uprintf("\r\nVrse_B:        Electrical bias on ISFET voltage so that 7pH is 0V with respect to external reference");
            uprintf("\r\nVk:            Between -1.5 and -0.7, expected to move around");
            uprintf("\r\nIk:            15uV/nA + amplifier offset (~800uV).  Should be < ~20nA");
            uprintf("\r\nIb:            1mV/nA.   Should be < 10nA");
            uprintf("\r\n");
            uprintf("\r\n");
            wait_consoleTx();
            break;
        case 'q':
            uprintf("\r\nExperimental menus disabled\r\n");
            sys_data.app_cfg[APPCFG_MENU_LEVEL] = 0;
            sys_data.diag = 0;
            break;
        case 'Q':
            uprintf("\r\nExperimental menus enabled, sys_data.app_cfg[APPCFG_MENU_LEVEL] = 1\r\n");
            sys_data.diag = 1;
            sys_data.app_cfg[APPCFG_MENU_LEVEL] = 1;
            break;
        case 'z':
            if(sys_data.app_cfg[APPCFG_MENU_LEVEL] == 1)
            {
                uprintf("\r\nDebug Printf statements are disabled\r\n");
                sys_data.debug_flag = 0;
                dbg_flag = sys_data.debug_flag;
            }
            break;
        case 'Z':
            if(sys_data.app_cfg[APPCFG_MENU_LEVEL] == 1)
            {
                uprintf("\r\nDebug Printf statements are enabled\r\n");
                sys_data.debug_flag = 1;
                dbg_flag = sys_data.debug_flag;
            }
            break;
        case 's':
        case 'S':
            uprintf("\r\n\r\n--------- ADC24 Sample Times ---------------\r\n");

            uprintf("User variables for trials and sps:\r\n");
            uprintf("VTherm=%4u ms,   trials=%2u, sps=%u\r\n", (uint32_t)(1000*sys_data.Vtherm_trials * (float)(1/(float)sys_data.Vtherm_sps)), (unsigned int)sys_data.Vtherm_trials, (unsigned int)sys_data.Vtherm_sps);
            uprintf("  Vrsi=%4u ms,   trials=%2u, sps=%u\r\n", (uint32_t)(1000*sys_data.Vrsi_trials * (float)(1/(float)sys_data.Vrsi_sps)), (unsigned int)sys_data.Vrsi_trials, (unsigned int)sys_data.Vrsi_sps);
            uprintf("  Vrse=%4u ms,   trials=%2u, sps=%u\r\n", (uint32_t)(1000*sys_data.Vrse_trials * (float)(1/(float)sys_data.Vrse_sps)), (unsigned int)sys_data.Vrse_trials, (unsigned int)sys_data.Vrse_sps);
            uprintf("    Ik=%4u ms,   trials=%2u, sps=%u\r\n", (uint32_t)(1000*sys_data.Ik_trials * (float)(1/(float)sys_data.Ik_sps)), (unsigned int)sys_data.Ik_trials, (unsigned int)sys_data.Ik_sps);

            uprintf("    Vk=%4u ms,   trials=%2u, sps=%u\r\n", (uint32_t)(1000*sys_data.Vk_trials * (float)(1/(float)sys_data.Vk_sps)), (unsigned int)sys_data.Vk_trials, (unsigned int)sys_data.Vk_sps);
            uprintf("    Ib=%4u ms,   trials=%2u, sps=%u\r\n", (uint32_t)(1000*sys_data.Ib_trials * (float)(1/(float)sys_data.Ib_sps)), (unsigned int)sys_data.Ib_trials, (unsigned int)sys_data.Ib_sps);
            uprintf("    Vb=%4u ms,   trials=%2u, sps=%u\r\n", (uint32_t)(1000*sys_data.Vb_trials * (float)(1/(float)sys_data.Vb_sps)), (unsigned int)sys_data.Vb_trials, (unsigned int)sys_data.Vb_sps);
            uprintf(" Vbias=%4u ms,   trials=%2u, sps=%u\r\n", (uint32_t)(1000*sys_data.Vbias_trials * (float)(1/(float)sys_data.Vbias_sps)), (unsigned int)sys_data.Vbias_trials, (unsigned int)sys_data.Vbias_sps);

            uprintf("\r\n\r\n");
            break;
        default:
            return;
            break;
        }
    } // while(1)


}






















// easter egg for an mbari user of phfet-sos that has been kicked a bit by life, in hopes it brings a smile
const char* wisdom_arr[] =
{
    "As a rule, you will get out of it what you put into it.",
    "Life is not fair.  Don’t expect it to be.",
    "You have to be at the table to win.  Give yourself a fighting chance.  Get in the game.",
    "90% of what you worry about won’t happen.",
    "Much of what \"everybody knows\" is based on bad information.  Never be afraid to question what \"everybody knows\"",
    "Sometimes people with the best of intentions and high character will let you down.  Seek guidance, do your research, but always make your own decisions.",
    "Never, ever measure your worth by the size of your bank account.",
    "Most kids would benefit from a summer or two of hard physical labor.",
    "Despite what we were told as kids, not all of us can be \"anything we want to be\".  Some of us simply lack the necessary skill sets - And that’s Ok.",
    "Play to your strengths.",
    "Work on to your weaknesses.",
    "Life’s personal tragedies aren’t always disasters.  Sometimes they are the setup to something great that couldn’t come about any other way.",
    "Be open to friendship from anybody.  Some of my best friends started out as the most unlikely.",
    "Work with a net whenever possible, but NEVER be afraid to take a risk.",
    "Never take advice from a cynic.",
    "Make a coast to coast drive across the U.S. at least once.",
    "Learn the language.  Words have meaning.  A misused, expensive word can cause you to lose credibility.",
    "See a doctor for a full physical at least once a year.",
    "To the greatest extent possible, don’t act or speak out of anger.  Too much damage can be done, and some of it cannot be undone.",
    "Eliminate vices everywhere possible.  There is always some price to be paid for them.",
    "Stay curious about the world and never let the fear of appearing ignorant stop you from asking questions.  Nobody is born knowing anything.",
    "Mental health should be treated no differently than physical health.  We don’t feel shame if we break an arm or spot a new, oddly shaped mole.  We tend to it.  If your brain is broken – tend to it.",
    "Cognitive dissonance renders the arguing of deeply held beliefs virtually pointless.",
    "It is much easier to stay in shape than it is to get in shape.",
    "The music of each generation, with certain exceptions, is largely ephemeral.  But Bach, Beethoven, Mozart, and Vivaldi live on.  There is a reason for that.",
    "Some people, for reasons they don’t even understand, are simply not going to like you.  Learn this as early in life as possible, accept it, and don’t lose a wink of sleep over it.  It’s not your problem.",
    "The soul needs time in nature to recenter itself.  Mountains, Oceans, Forests, and vast Prairie lands have seen billions of days, and they have a way of putting our day to day troubles in proper perspective.",
    "Sir Isaac Newton was right – Entropy increases.  Things must be tended to regularly.",
    "Don’t be too quick to judge.  Life altering mistakes can be made from a hasty misperception.",
    "Learn to argue both sides of any issue as if you had to defend it in court.",
    "Always buy something from a kid selling anything.",
    "An ounce of prevention truly is worth a pound of cure.",
    "Political arguments are pointless.  Avoid them.",
    "Mental health should be treated no differently than physical health.  We don’t feel shame if we break an arm or spot a new, oddly shaped mole.  We tend to it.  If your brain is broken – tend to it without shame.",
    "Homemade anything is better than store bought.",
    "Everybody has a story and most of them are quite interesting.  Take the time to listen.",
    "Procrastination is not your friend.",
    "Taking a good shot and missing is far better than the regret of not taking the shot at all.",
    "Don’t overthink it.",
    "Sometimes in working through a problem, you can be doing everything right but get to a solution.  In those cases, the missing variable is just \"time\".  Be Patient.",
    "Be sure that what you heard is what they actually meant.",
    "Data may not lie, but results can be manipulated and filtered.",
    "Be very careful about what you say to a kid and how you say it.  You never know what a kid is going to remember, and many times it will just be a passing, fleeting, comment.",
    "When people tell you to \"enjoy it while you can, because you’ll miss it when it’s gone\", listen carefully.  There is a reason they’re saying that.",
    "The feeling of finding or losing a love is the same at 50 as it is at 15.",
    "Save painting with a broad brush for barns.  It is otherwise not a good idea.",
    "Never compare yourself to others.  Compare yourself to your own potential.",
    "The one doing all the talking is the ringleader, and usually the more they say, the less able they are to back it up.",
    "Some set of circumstances brought everybody to where they are now.  Don’t judge too harshly.",
    "Don’t take a window seat and then ride the whole way with the shade pulled down.",
    "Take some self defense training or play a combative sport for a while, even if you never get good at it.",
    "Invest in people.  Most of the best memories of your life are not made alone.",
    "Whatever the dress code at a meeting – kick it up a notch.",
    "Coach a little league team at least once.",
    "Karma, or whatever you want to call it, is real.  What you put out will eventually come back around.",
    "Never put off calling an old friend.",
    "Never let anybody substitute caramel for butterscotch.  They are not the same thing.",
    "The situation usually isn’t as good or bad as it seems.",
    "Simple answers are for simple minds.  Dig deep.  Ask tough questions",
    "Yogi Berra was right – \"It ain’t over til it’s over.\"",
    "Measure twice, cut once.",
    "There are known knowns; things we know we know. We also know there are known unknowns; we know there are some things we do not know. But, there are also unknown unknowns - the ones we don't know we don't know.",
    "Know no thing is perfect and as well nothing is perfect",
    "An unmoving snail is sitting, standing, lying",
    "If you die, you are dead",
    "They dont think it be like it is, but it do",
    "Choose your parents wisely."
    ,0
};

//     "The soul needs time in nature to recenter itself.  Mountains, Oceans, Forests, and vast Prairie lands have seen billions of days, and they have a way of putting our contracts, meetings, projects, and reports, into perspective.",
//     "Mental health should be treated no differently than physical health.  We don’t feel shame if we break an arm or spot a new, oddly shaped mole.  We tend to it.  If your brain is broken – tend to it, and don’t feel an ounce of shame about it.",
//    "There are known knowns; things we know we know. We also know there are known unknowns; we know there are some things we do not know. There are also unknown unknowns - the ones we don't know we don't know. \r\nknow no thing is perfect",

