Process GET query request to normalize query arguments (split lists, etc)

    TODO: Generalize this for any list of API variables/strings and separators for lists

    Returns context dict with these updated elements:
    context['form']                a Form object populated with the normalized form field values from the GET query
    context['form_is_valid']       True  or False
    context['errors']              list of validation error messages to be displayed at top of form
    context['plot']                normalized acronym for one of 4 histogram type: 'hist', 'pmf', 'cmf', or 'cfd'
    contexxt['plot_name']          descriptive name for the plot type: 'Histogram', 'Probability Mass Function' ...
    context['table']               'fast' or 'detailed'
    context['limit']               int indicating the maximum number of rows (for speeding the query for a detailed table)
    context['regex']               regular expression string to test whether inspection notes and comments match
    context['columns']             columns to display in quicktable and csv
    context['filter']              dict for use in a Django queryset filter:
    {
        'model_numbers': mn.split(',')  #    list of strings for ?mn=
        'sales_groups': sg.split(',')  #     list of strings for ?sg=
        'fiscal_years': sn.split(',')  #     list of strings for ?fy=
        'reasons': sn.split(',')  #          list of strings for ?r=
        'account_numbers': an.split(',')  #  list of strings for ?an=
        'min_dates': sn.split(',')  #        list of strings for ?min_date=
        'max_dates': sn.split(',')  #        list of strings for ?max_date=
        'min_lag': sn.split(',')  #          list of strings for ?min_lag=
        'max_lag': sn.split(',')  #          list of strings for ?max_lag=
        'exclude': sn.split(',')  #          "E" or "I" (include or exclude account numbers)
        'columns': columns.split(';')  #          list of fields for columns of CSV
    }

def context_from_request(request, context=None, Form=GetLagForm, delim=',', verbosity=0, **kwargs):
    """Process GET query request to normalize query arguments (split lists, etc)

    TODO: Generalize this for any list of API variables/strings and separators for lists

    Returns context dict with these updated elements:
    context['form']                a Form object populated with the normalized form field values from the GET query
    context['form_is_valid']       True  or False
    context['errors']              list of validation error messages to be displayed at top of form
    context['plot']                normalized acronym for one of 4 histogram type: 'hist', 'pmf', 'cmf', or 'cfd'
    contexxt['plot_name']          descriptive name for the plot type: 'Histogram', 'Probability Mass Function' ...
    context['table']               'fast' or 'detailed'
    context['limit']               int indicating the maximum number of rows (for speeding the query for a detailed table)
    context['regex']               regular expression string to test whether inspection notes and comments match
    context['columns']             columns to display in quicktable and csv
    context['filter']              dict for use in a Django queryset filter:
    {
        'model_numbers': mn.split(',')  #    list of strings for ?mn=
        'sales_groups': sg.split(',')  #     list of strings for ?sg=
        'fiscal_years': sn.split(',')  #     list of strings for ?fy=
        'reasons': sn.split(',')  #          list of strings for ?r=
        'account_numbers': an.split(',')  #  list of strings for ?an=
        'min_dates': sn.split(',')  #        list of strings for ?min_date=
        'max_dates': sn.split(',')  #        list of strings for ?max_date=
        'min_lag': sn.split(',')  #          list of strings for ?min_lag=
        'max_lag': sn.split(',')  #          list of strings for ?max_lag=
        'exclude': sn.split(',')  #          "E" or "I" (include or exclude account numbers)
        'columns': columns.split(';')  #          list of fields for columns of CSV
    }
    """
    context = context or RequestContext(request)

    context['errors'] = []
    context['filter'] = {}

    limit = request.GET.get('limit') or request.GET.get('num') or request.GET.get('num_rows') or request.GET.get('rows') or request.GET.get('records') or request.GET.get('count', 0)

    context['plot'] = (request.GET.get('plot', '') or request.GET.get('plt', '') or request.GET.get('p', '') 
                        or request.GET.get('chart', '') or request.GET.get('chrt', '')
                        ).strip().lower()
    context['plot'] = util.HIST_NAME.get(context['plot'][-3:], context['plot'])
    context['plot_name'] = util.HIST_CONFIG[context['plot']]['name'] if context['plot'] else ''


    context['table'] = (request.GET.get('table', '') or request.GET.get('tbl', '') or request.GET.get('tble', '') 
                        or request.GET.get('tab', '') or request.GET.get('t', '')
                        ).strip().lower()
    if context['table'].startswith('f'):
        context['table'] = 'fast'
    if context['table'].startswith('a'):
        context['table'] = 'aggregate'
        context['aggregates'] = []
        # context['plot'] = 'aggregate'
    if context['table'].startswith('d'):
        context['table'] = 'detailed'
        limit = limit or 10*1000
    context['limit'] = util.make_int(limit)

    mn = request.GET.get('mn', "") or request.GET.get('model', "") or request.GET.get('models', "") or request.GET.get('model_number', "") or request.GET.get('model_numbers', "")
    mn = [s.strip().upper() for s in mn.split(',')] or ['']
    context['filter']['model_numbers'] = mn

    sg = request.GET.get('sg', "") or request.GET.get('group', "") or request.GET.get('sales', "") or request.GET.get('sales_group', "") or request.GET.get('sale_group_number', "")
    sg = [s.strip().upper() for s in sg.split(',')] or ['']
    # need to implement filters on sales_group (where serial_numbers was, in explore_lags, and filter_sla_lags or lags_dict)
    context['filter']['sales_groups'] = sg

    fy = request.GET.get('fy', "") or request.GET.get('yr', "") or request.GET.get('year', "") or request.GET.get('years', "") or request.GET.get('fiscal_year', "") or request.GET.get('fiscal_years', "")
    fiscal_years = [util.normalize_year(y) for y in fy.split(',')] or []
    fiscal_years = [str(y) for y in fiscal_years if y]
    context['filter']['fiscal_years'] = fiscal_years

    rc = request.GET.get('r', "") or request.GET.get('rc', "") or request.GET.get('rcode', "") or request.GET.get('reason', "") or request.GET.get('reasons', "")
    context['filter']['reasons'] = [s.strip().upper() for s in rc.split(',')] or ['']

    an = request.GET.get('a', "") or request.GET.get('an', "") or request.GET.get('account', "") or request.GET.get('account_number', "") or request.GET.get('account_numbers', "")
    context['filter']['account_numbers'] = [s.strip().upper() for s in an.split(',')] or []

    exclude = request.GET.get('exclude', "") or request.GET.get('e', "") or request.GET.get('x', "") or request.GET.get('ex', "") or request.GET.get('excl', "I")
    context['exclude'] = 'E' if exclude.upper().startswith('E') else ''

    min_dates = request.GET.get('mind') or request.GET.get('min_date') or request.GET.get('min_dates') or ""
    min_dates = [s.strip() for s in min_dates.split(',')] or ['']
    context['filter']['min_dates'] = min_dates

    max_dates = request.GET.get('maxd') or request.GET.get('max_date') or request.GET.get('max_dates') or ""
    max_dates = [s.strip() for s in max_dates.split(',')] or ['']
    context['filter']['max_dates'] = max_dates

    context['regex'] = request.GET.get('re') or request.GET.get('regex') or request.GET.get('word') or request.GET.get('search') or request.GET.get('find') or ""

    context['columns'] = request.GET.get('col') or request.GET.get('cols') or request.GET.get('column') or request.GET.get('columns') or ""
    context['columns'] = [s.strip() for s in context['columns'].split(';')] or []

    context['aggregate_ids'] = request.GET.get('agg') or request.GET.get('ids') or request.GET.get('aggids') or request.GET.get('aggregates') or request.GET.get('aggregate_ids') or '-1'
    context['aggregate_ids'] = [int(s.strip()) for s in context['aggregate_ids'].split(',') if s and s.strip()] or [-1]

    # whether the FK join queries should be short-circuited
    if verbosity > 0:
        print('aggregate_ids: ', context['aggregate_ids'])
    context['quick'] = context.get('quick') or (context['table'].startswith('agg') and context['aggregate_ids'] and not (context['aggregate_ids'][-1] == -1) and not context['table'] == 'fast')
    if verbosity > 0:
        print(context['quick'])

    # lag values can't be used directly in a django filter so don't put them in context['filter']
    lag = request.GET.get('lag', '') or request.GET.get('l', '')
    lag = [s.strip().upper() for s in lag.split(',')] or ['']
    maxl = request.GET.get('max_lag', '') or request.GET.get('maxlag', '') or request.GET.get('maxl', '')
    minl = request.GET.get('min_lag', '') or request.GET.get('minlag', '') or request.GET.get('maxl', '')

    try:
        lag = int(lag)
        minl = lag - 7
        maxl = lag
    except:
        try:
            minl = int(minl)
        except:
            minl = ''
        try:
            maxl = int(maxl)
        except:
            maxl = ''

    context['filter']['min_lag'] = minl
    context['filter']['max_lag'] = maxl

    initial = {
                'mn':       ', '.join(m.strip() for m in context['filter']['model_numbers'] if m.strip()), 
                'sg':       ', '.join(context['filter']['sales_groups']),
                'r':        ', '.join(context['filter']['reasons']),
                'an':       ', '.join(context['filter']['account_numbers']),
                'fy':       ', '.join(context['filter']['fiscal_years']),
                'exclude':            context['exclude'],
                'min_lag':            context['filter']['min_lag'],
                'max_lag':            context['filter']['max_lag'],
                'min_date': ', '.join(context['filter']['min_dates']),
                'max_date': ', '.join(context['filter']['max_dates']),
                'columns':  '; '.join(context['columns']),
                'regex':              context['regex'],
                'name':        ''
              }

    context['name'] = request.GET.get('s') or request.GET.get('n') or request.GET.get('series') or request.GET.get('name') or util.slug_from_dict(initial)

    if verbosity > 0:
        print 'initial: {0}'.format(initial)
        print 'normalized GET query parameters: %r' % initial
        print 'Form before validation {0}'.format(Form)

    if request.method == 'POST':
        # GetLagForm only has a GET button
        context['form'] = Form(request.POST)
    elif request.method == 'GET':
        context['form'] = Form(data=initial, initial=initial)
    if verbosity > 0:
        print Form

    context['form_is_valid'] = context['form'].is_valid()
    if not context['form_is_valid']:
        context['form_errors'] = context['form'].errors
        if verbosity > 0:
            print 'ERRORS in FORM !!!!!!!!!!!!!'
            print context['form_errors']
        #import ipdb
        #ipdb.set_trace()
        #raise RuntimeError('form is invalid')

    if not context.get('field_names'):
        context['field_names'] = kwargs.get('field_names', [])

        
    if not context.get('filename'):
        context['filename'] = 'Refurb.csv'

    return context