"""
w2lapp.searchform.py: different search forms

web2ldap - a web-based LDAP Client,
see http://www.web2ldap.de for details

(c) by Michael Stroeder <michael@stroeder.com>

This module is distributed under the terms of the
GPL (GNU GENERAL PUBLIC LICENSE) Version 2
(see http://www.gnu.org/copyleft/gpl.html)

$Id: searchform.py,v 1.17 2002/02/20 20:31:29 michael Exp $
"""

import ldap,pyweblib.forms,w2lapp.core,w2lapp.gui,w2lapp.cnf

searchform_mode_text = {
  'adv':'Advanced',
  'base':'Basic',
  'exp':'Expert',
}

search_options = (
  (r'(%s=*%s*)',u'contains'),
  (r'(%s=*)',u'exists'),
  (r'(!(%s=*%s*))',u"doesn't contain"),
  (r'(%s=%s)',u'is'),
  (r'(!(%s=%s))',u'is not'),
  (r'(%s=%s*)',u'begins with'),
  (r'(%s=*%s)',u'ends with'),
  (r'(%s~=%s)',u'sounds like'),
  (r'(%s>=%s)',u'greater equal than'),
  (r'(%s<=%s)',u'lesser equal than')
)

def SearchForm_begin(sid,outf,command,form,ls,searchform_mode,Msg=''):
  outf.write("""
    <div id="InputDiv">
      <h1>%s Search Form</h1>
      <form
        action="%s/search/%s"
        method="GET"
        enctype="application/x-www-form-urlencoded"
        accept-charset="%s"
      >
      %s
      """ % (
      searchform_mode_text[searchform_mode],
      form.script_name,
      sid,
      form.accept_charset,
      Msg,
    )
  )


def SearchForm_exp(sid,outf,command,form,ls,dn,search_filterstr='()'):
  """Output expert search form"""
  # expert search form for using LDAP filters
  if 'search_filterstr' in form.inputFieldNames:
    search_filterstr = form.field['search_filterstr'].value[0]
  outf.write("""
    LDAP filter string<BR>
    <input name="search_filterstr" maxlength="120" size="60" value="%s">
    """ % (
      search_filterstr.encode(form.accept_charset),
    )
  )


def SearchForm_base(sid,outf,command,form,ls,dn):
  """Output basic search form"""
  searchform_template_filename = w2lapp.gui.GetVariantFilename(
    w2lapp.cnf.GetParam(ls,'searchform_template',''),
    form.accept_language
  )
  if searchform_template_filename:
    try:
      template_str = open(searchform_template_filename,'r').read()
    except IOError:
      outf.write('<div id=MessageDiv><p>I/O error during reading template file.</p></div>')
    else:
      outf.write(template_str)
  else:
    outf.write('<div id=MessageDiv><p>Template file not found.</p></div>')


def SearchForm_adv(sid,outf,command,form,ls,dn):
  """advanced search form with select lists"""

  rows = int(form.getInputValue('search_params',['1'])[0])
  if rows<1:
    rows = 1
  if rows>w2lapp.cnf.misc.max_searchparams:
    rows = w2lapp.cnf.misc.max_searchparams

  outf.write('<div id="InputDiv">\n<h1>Advanced Search Form</h1>\n')

  # More and Fewer-Buttons
  outf.write('<table><tr>')
  if rows<w2lapp.cnf.misc.max_searchparams:
    outf.write(
      '<td>%s</td>' % w2lapp.gui.W2L_Anchor(
	form,'searchform','More',sid,
        [
          ('dn',dn),
          ('searchform_mode','adv'),
          ('search_params',str(rows+1)),
        ],
      )
    )
  if rows>1:
    outf.write('<td>%s</td>' % w2lapp.gui.W2L_Anchor(
        form,'searchform','Fewer',sid,
        [
          ('dn',dn),
          ('searchform_mode','adv'),
          ('search_params',str(rows-1)),
        ],
      )
    )

  outf.write('<td>search parameters</td></tr></table>')

  search_mode_select = pyweblib.forms.Select(
    'search_mode',
    u'Search mode',1,
    options=[(ur'(&%s)',u'all'),(ur'(|%s)',u'any')]
  )
  search_mode_select.setCharset(form.accept_charset)
  search_attrs = w2lapp.cnf.GetParam(ls,'search_attrs',['cn','mail'])

  # Eigentliches Suchformular ausgeben
  outf.write("""
    <form 
      action="%s/search/%s"
      method="GET"
      enctype="application/x-www-form-urlencoded"
      accept-charset="%s"
    >
    Match %s of the following.<br>
    """ % (
      form.script_name,
      sid,
      form.accept_charset,
      search_mode_select.inputHTML()
    )
  )

  search_attr_list = []
  for attr in search_attrs:
    search_attr_list.append((attr,w2lapp.core.ldap_knownattr.get(attr,attr)))
  search_attr_select = pyweblib.forms.Select(
    'search_attr',u'Search attribute type',
    w2lapp.cnf.misc.max_searchparams,
    options=search_attr_list
  )
  search_attr_select.setCharset(form.accept_charset)
  search_option_select = pyweblib.forms.Select(
    'search_option','Search option',
    w2lapp.cnf.misc.max_searchparams,
    options=search_options
  )
  search_option_select.setCharset(form.accept_charset)
  # Output a row of the search form
  for i in range(rows):
    search_attr_select.setDefault(search_attrs[i % len(search_attrs)])
    outf.write('%s\n%s\n' % (search_attr_select.inputHTML(),search_option_select.inputHTML()))
    # Output of search string input field
    outf.write('<input name="search_string" maxlength="60" size="30" value=""><br>\n')


def w2l_SearchForm(
  sid,outf,command,form,ls,dn,
  searchform_mode='base',
  Msg='',
  search_filterstr='()',
  scope=ldap.SCOPE_SUBTREE
):
  """Output a search form"""

  searchform_mode = form.getInputValue('searchform_mode',[searchform_mode])[0]
  search_root = form.getInputValue('search_root',[dn])[0]

  ContextMenuList = [
    w2lapp.gui.W2L_Anchor(
      form,'searchform',searchform_mode_text[mode],sid,
      [
        ('dn',dn),
        ('searchform_mode',mode),
        ('search_root',search_root),
        ('search_filterstr',search_filterstr),
        ('scope',str(scope)),
      ],
    )
    for mode in searchform_mode_text.keys()
    if mode!=searchform_mode
  ]

  w2lapp.gui.TopSection(
    sid,outf,form,ls,dn,
    '%s Search Form' % searchform_mode_text[searchform_mode],
    w2lapp.gui.MainMenu(sid,form,ls,dn),
    context_menu_list=ContextMenuList
  )

  if searchform_mode == 'base':
    # base search form with fixed input fields
    SearchForm_begin(sid,outf,command,form,ls,searchform_mode,Msg)
    SearchForm_base(sid,outf,command,form,ls,dn)
  elif searchform_mode == 'exp':
    # expert search form with single filter input field
    SearchForm_begin(sid,outf,command,form,ls,searchform_mode,Msg)
    SearchForm_exp(sid,outf,command,form,ls,dn,search_filterstr)
  elif searchform_mode == 'adv':
    # base search form with fixed input fields
    SearchForm_adv(sid,outf,command,form,ls,dn)

  search_root_field = w2lapp.gui.SearchRootField(form,ls,dn)
  if 'search_root' in form.inputFieldNames:
    search_root_field.setDefault(form.field['search_root'].value[0])

  search_scope_field = pyweblib.forms.Select(
    'scope','Scope',1,
    options=[
      (str(ldap.SCOPE_BASE),'Base'),
      (str(ldap.SCOPE_ONELEVEL),'One level'),
      (str(ldap.SCOPE_SUBTREE),'Sub tree')
    ],
    default=form.getInputValue('scope',[str(scope)])[0]
  )
  search_resnumber_field = pyweblib.forms.Select(
    'search_resnumber',
    u'Number of results to display',
    1,
    options=[(u'0',u'unlimited'),(u'10',u'10'),(u'20',u'20'),(u'50',u'50'),(u'100',u'100'),(u'200',u'200')],
    default=str(w2lapp.cnf.GetParam(ls,'search_resultsperpage',10))
  )

  # Output of form part for all kind of search forms
  outf.write("""
<p>
 Search root
 %s
 Scope %s
 Results per page %s
</p>
 <input type="submit" value="Search">
 <input type="reset" value="Reset">
 </form>
</div>
""" % (
    search_root_field.inputHTML(),
    search_scope_field.inputHTML(),
    search_resnumber_field.inputHTML(),
  ))

  w2lapp.gui.PrintFooter(outf,form)

