// $Id$
// Copyright 2004 Nokia Corporation.
//
// THIS SOURCE CODE IS PROVIDED 'AS IS', WITH NO WARRANTIES WHATSOEVER,
// EXPRESS OR IMPLIED, INCLUDING ANY WARRANTY OF MERCHANTABILITY, FITNESS
// FOR ANY PARTICULAR PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE
// OR TRADE PRACTICE, RELATING TO THE SOURCE CODE OR ANY WARRANTY OTHERWISE
// ARISING OUT OF ANY PROPOSAL, SPECIFICATION, OR SAMPLE AND WITH NO
// OBLIGATION OF NOKIA TO PROVIDE THE LICENSEE WITH ANY MAINTENANCE OR
// SUPPORT. FURTHERMORE, NOKIA MAKES NO WARRANTY THAT EXERCISE OF THE
// RIGHTS GRANTED HEREUNDER DOES NOT INFRINGE OR MAY NOT CAUSE INFRINGEMENT
// OF ANY PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OWNED OR CONTROLLED
// BY THIRD PARTIES
//
// Furthermore, information provided in this source code is preliminary,
// and may be changed substantially prior to final release. Nokia Corporation
// retains the right to make changes to this source code at
// any time, without notice. This source code is provided for informational
// purposes only.
//
// Nokia and Nokia Connecting People are registered trademarks of Nokia
// Corporation.
// Java and all Java-based marks are trademarks or registered trademarks of
// Sun Microsystems, Inc.
// Other product and company names mentioned herein may be trademarks or
// trade names of their respective owners.
//
// A non-exclusive, non-transferable, worldwide, limited license is hereby
// granted to the Licensee to download, print, reproduce and modify the
// source code. The licensee has the right to market, sell, distribute and
// make available the source code in original or modified form only when
// incorporated into the programs developed by the Licensee. No other
// license, express or implied, by estoppel or otherwise, to any other
// intellectual property rights is granted herein.

package sendSms;

import java.util.*;
import javax.microedition.lcdui.*;
import javax.microedition.pim.*;

// This Form shows a list of the contacts in the local databases
class ContactListForm
  extends List
  implements CommandListener
{
  private final Command exitCommand, selectCommand, backCommand;
  private final Ticker ticker;
  private final BetamaxSMS parent;
  private boolean available;
  private boolean done;
  private boolean mobOnly;
  private String hint;
  private Vector allTelNumbers = new Vector();


  public ContactListForm(BetamaxSMS parent)
  {
    super("Contacts", Choice.IMPLICIT);
    this.parent = parent;
    this.mobOnly = parent.mobOnly.equals("yes");
    hint = parent.recipient.getString().toLowerCase();
    
    done=false;

    // init UI
    selectCommand = new Command("Select", Command.OK, 0);
    backCommand = new Command("Back", Command.BACK, 1);
    exitCommand = new Command("Exit", Command.EXIT, 1);
    ticker = new Ticker("searching");

    addCommand(backCommand);
//    addCommand(exitCommand);
    addCommand(selectCommand);
    setTicker(ticker);
    setCommandListener(this);
    
    setFitPolicy(Choice.TEXT_WRAP_ON);
  
    // load the list of names in different thread
    LoadContacts c = new LoadContacts();
    c.start();
  }


  public void commandAction(Command cmd, Displayable displayable)
  {
//    parent.showMessage("Command:\n"+cmd.getLabel()+"\n"+cmd.getLongLabel(), this);
    // if no names are available return
    if (!available)
    {
      parent.showMain();
      return;
    }
    else if (cmd == backCommand)
    {
      parent.showMain();
    }
    else if (cmd == exitCommand)
    {
      parent.notifyDestroyed();
    } else //if (cmd == selectCommand)
    {
      int selected = getSelectedIndex();
      if (selected >= 0)
      {
        // will get the number from the list
        parent.contactSelected((String) allTelNumbers.elementAt(selected));
        done = true;
        parent.showMain();
      }
      else
      {
        parent.showMessage("Nothing selected!",this);
      }
    }   
  }


  // loads the names of a named contact list
  private void loadNames(String name)
    throws PIMException, SecurityException
  {
    ContactList contactList = null;
    try
    {
      int nameField=-1;
      contactList = (ContactList) PIM.getInstance()
        .openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY, name);

      if (contactList.isSupportedField(Contact.NAME))
        nameField=Contact.NAME;
      
      if (contactList.isSupportedField(Contact.FORMATTED_NAME))
        nameField=Contact.FORMATTED_NAME;
      
      // First check that the fields we are interested in are supported
      // by the PIM List
      if (nameField >=0 && contactList.isSupportedField(nameField)
          && contactList.isSupportedField(Contact.TEL))
      {
        // Put an informative title while reading the contacts
        setTitle("Contacts");
        append("Reading contacts...", null);
        Enumeration items = contactList.items();
        // change the title to use the localized name.
        // getFieldLabel returns an i18n version
        delete(0);
        setTitle(contactList.getFieldLabel(nameField)
                 + ": "
                 + contactList.getFieldLabel(Contact.TEL));
        Vector telNumbers = new Vector();
        while (!done && items.hasMoreElements())
        {
          String contactName;
          Contact contact = (Contact) items.nextElement();
          int telCount = contact.countValues(Contact.TEL);
          int nameCount = contact.countValues(nameField);

          available = true;
          
          // we're only interested on contacts with a phone number
          // nameCount should always be > 0 since FORMATTED_NAME is mandatory
          if (telCount > 0 && nameCount > 0 &&
              (contactName = getName(contact, nameField)).toLowerCase().indexOf(hint)>=0)
          {
            // go through all the phone numbers
            for (int i = 0; !done && i < telCount; i++)
            {
              // check if it is a cell phone and put it at the begining
              // this doesn't necessary work since in many cases is up
              // to the user to indicate whether it is a mobile phone
              int telAttributes =
                contact.getAttributes(Contact.TEL, i);
              String telNumber =
                contact.getString(Contact.TEL, i);
              // check if ATTR_MOBILE is supported
              if (contactList.
                isSupportedAttribute(Contact.TEL,
                                     Contact.ATTR_MOBILE))
              {
                if ((telAttributes & Contact.ATTR_MOBILE) != 0)
                {
                  telNumbers.insertElementAt(telNumber, 0);
                }
                else if(!mobOnly)
                {
                  telNumbers.addElement(telNumber);
                }
              }
              else
              {
                telNumbers.addElement(telNumber);
              }
            }
            // Shorten names which are too long
            if (contactName.length()>30)
            {
              contactName = contactName.substring(0, 27)
                + "...";
            }
            // insert elements in the list in order
            for (int i = 0; i < telNumbers.size(); i++)
            {
              append(contactName
                + ": "
                + telNumbers.elementAt(i), null);
              allTelNumbers.addElement(telNumbers.elementAt(i));
            }
            telNumbers.removeAllElements();
          }
        }
      }
      else
      {
        append("Contact list required items not supported", null);
        available = false;
      }
    }
    finally
    {
      // always close it
      if (contactList != null)
      {
        contactList.close();
      }
    }
  }
  
  // Lookup name using FORMATTED_NAME or NAME_FAMILY + NAME_GIVEN
  public String getName(Contact c, int nameField){
    if (nameField == Contact.FORMATTED_NAME){
        String rname = null;
/* already counted above       
        if(c.countValues(Contact.FORMATTED_NAME) > 0)
 */
            rname = c.getString(Contact.FORMATTED_NAME, 0);

        if(rname.length() > 0)
            return rname;
    }
    if (nameField == Contact.NAME){
/* already countend above
        if(c.countValues(Contact.NAME) == 0)
            return null;
*/
        String[] name = c.getStringArray(Contact.NAME, 0);
        String first = null;
        String last = null;
        if (c.getPIMList().isSupportedArrayElement(Contact.NAME, Contact.NAME_FAMILY))
              last = name[Contact.NAME_FAMILY];
        if (c.getPIMList().isSupportedArrayElement(Contact.NAME, Contact.NAME_GIVEN))
              first = name[Contact.NAME_GIVEN];
        int sum = 2*(first==null?0:1) + (last==null?0:1);
        switch(sum){
        case 1:
            return last;
        case 2:
            return first;
        case 3:
            return first + " " + last;
        default:
            return null;
        }
    } else 
        return null;
}


  // load the names
  //private class LoadContacts implements Operation
  private class LoadContacts extends Thread
  {
    public void run()
    {
      try
      {
        // go through all the lists
        String[] allContactLists = PIM.getInstance()
          .listPIMLists(PIM.CONTACT_LIST);
        if (allContactLists.length != 0)
        {
          for (int i = 0; !done && i < allContactLists.length; i++)
          {
            loadNames(allContactLists[i]);
          }
          if(allTelNumbers.isEmpty()) {
            removeCommand(selectCommand);
            getTicker().setString("search failed");
            append("No items matching '"+hint+"'",null);
          } else if(parent.autoSelect.equals("yes") && allTelNumbers.size()==1){
              parent.contactSelected((String) allTelNumbers.elementAt(0));
              done = true;
              parent.showMain();
          } else
            getTicker().setString("pick one");
        }
        else
        {
          append("No Contact lists available", null);
          available = false;
        }
      }
      catch (PIMException e)
      {
        parent.showMessage(e.getMessage(), ContactListForm.this);
        available = false;
        append("Press a key to return", null);
      }
      catch (SecurityException e)
      {
        parent.showMessage(e.getMessage(), ContactListForm.this);
        available = false;
        append("Press a key to return", null);
      }
    }
  }
}

