/*
Copyright 1990-2001 Sun Microsystems, Inc. All Rights Reserved.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions: The above copyright notice and this
permission notice shall be included in all copies or substantial
portions of the Software.


THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE OPEN GROUP OR SUN MICROSYSTEMS, INC. BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE EVEN IF
ADVISED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.


Except as contained in this notice, the names of The Open Group and/or
Sun Microsystems, Inc. shall not be used in advertising or otherwise to
promote the sale, use or other dealings in this Software without prior
written authorization from The Open Group and/or Sun Microsystems,
Inc., as applicable.


X Window System is a trademark of The Open Group

OSF/1, OSF/Motif and Motif are registered trademarks, and OSF, the OSF
logo, LBX, X Window System, and Xinerama are trademarks of the Open
Group. All other trademarks and registered trademarks mentioned herein
are the property of their respective owners. No right, title or
interest in or to any trademark, service mark, logo or trade name of
Sun Microsystems, Inc. or its licensors is granted.

*/
#include "IIIMProtocol.hh"
#include "IIIMPClient.hh"
#include "IMProtoHandler.hh"
#include "IIIMPInputContext.hh"
#include "IMProtocolStructP.hh"
#include "ICAttribute.hh"
#if !defined(USE_FRAMEMGR_ALWAYS)
#else /* USE_FRAMEMGR_ALWAYS */
#include "FrameMgr.h"
#endif /* USE_FRAMEMGR_ALWAYS */
#include "IMTrans.hh"
#include "IMThread.hh"

IIIMPClient::
IIIMPClient(IIIMProtocol* imp, IMTransAccept* ss) {
  accept_fd = ss;
  im_id = accept_fd->connection_id();
  iiim_protocol = imp;

  being_deleted = False;
  respond_keepalive = False;

  application_name = "Unknown"; // get from IMClientName IMAttrib

  // IM Attribute List
  alloc_attr = active_attr = 0;
  imAttribute_list = 0;

  input_context_list.disable_reordering();

  // start creating a thread
  thread = new IMThread(socket_listener, this);
  // done creating a thread
}

IIIMPClient::
~IIIMPClient() {
  // remove self from im client list
  iiim_protocol->iiimp_client_list.remove(this);

  // call destory_ic methods for all input contexts
  InputContext *ic = &(input_context_list.getFirstItem());
  while(ic){
    if (ic && ((IIIMPInputContext*)ic)->is_active()) {
      input_context_list.remove(ic);
      ((IIIMPInputContext*)ic)->unrealize();
      iiim_protocol->proto_handler->DestroyIC((InputContext*)ic);
      // alive ICs should be delete here
      delete ic;
    }
    ic = &(input_context_list.getNextItem());
  }
  if(alloc_attr) {
	delete [] imAttribute_list;
  }
  delete accept_fd;
  accept_fd = 0;
  im_id = 0;
  delete thread;
}

void*
IIIMPClient::socket_listener(void* client_data) {
  IIIMPClient *client = (IIIMPClient*)client_data;
  unsigned char *message;
  int flag = True;

  // wait for IM_CONNECT message
  message = client->get_im_connect();
  client->dispatch(message, flag);
  if (flag == 1) delete message;

  while (1) {
    if (client->accept_fd == 0) return 0;
    switch (client->Select()) {
    case IMTransAccept::Trans_TIMEOUT:
      // timeout
      if (client->being_deleted) {
	delete client;
	return 0;
      }
      continue;
      break;
    case IMTransAccept::Trans_ACCEPT:
      // get a message
      client->being_deleted = False;
      if ((message = client->get_amessage()) == 0) {
	// client dies
	delete client;		// kill self
	return 0;
      }
      client->dispatch(message, flag);
      if (flag == 1) delete message;
      break;
    case IMTransAccept::Trans_ERROR:
    default:
      // error
      delete client;
      break;
    }
  }
  return 0;
}

int
IIIMPClient::write_data(const char *buf, int const len) const {
  const int max_byte = MAX_RW_DATA_LEN;
#ifdef WIN32
  size_t size = 0;
#else
  ssize_t size = 0;
#endif
  char *bufp = (char *)buf;

  if (accept_fd == 0) return 0;

  for (int rest_len = len; rest_len > 0;
       rest_len -= max_byte, bufp += max_byte) {
    if (rest_len < max_byte) {
      size += accept_fd->write(bufp, rest_len);
      break;
    } else {
      size += accept_fd->write(bufp, max_byte);
    }
  }
  return size;
}

int
IIIMPClient::read_data(const char *buf, const int len) const {
  const int max_byte = MAX_RW_DATA_LEN;
#ifdef WIN32
  size_t size = 0;
#else
  ssize_t size = 0;
#endif
  char *bufp = (char*)buf;
  int rest_len = len;

  if (accept_fd == 0) return 0;

  if (len == 0) // this should not happen
    return 0;

  // Read until nbytes have been read. We will break out when the following
  // two conditions occur:
  //  - num_read = 0 ( the connection has probably timed out )
  //  - accumulated size = expected nbyte.

  while (1) {
    int try_len = (rest_len < max_byte)? rest_len : max_byte;
    int num_read = accept_fd->read(bufp, try_len);
    if (num_read == 0)
      break;
    size += num_read;
    if (size == len)	// we have got our fill.
      break;
    bufp += num_read;
    rest_len -= num_read;
  }
  if (size == 0) { // lost the connection
    // kill the connection 
  }
  return size;
}

unsigned char*
IIIMPClient::get_im_connect() {
  IIimpProtoHdr hdr;
  int header_len = sizeof(IIimpProtoHdr);
#if !defined(USE_FRAMEMGR_ALWAYS)
#else /* USE_FRAMEMGR_ALWAYS */
  extern XimFrameRec im_packet_header_fr[];
#endif /* USE_FRAMEMGR_ALWAYS */

  while (1) {
    if (header_len != read_data((char *)&hdr, header_len)) {
      goto read_error;
    }
    if (hdr.opcode != IM_CONNECT) {
      // can do nothing
      continue;
    }
    int read_len;
    if ((read_len = read_data((char *)&byteOrder, sizeof(char)))
	!= sizeof(char)) {
      goto read_error;
    }
    need_swap = (byteOrder != iiim_protocol->byteOrder());
    return get_content((char*)&hdr, True);
  }
 read_error:
  delete accept_fd;
  im_id = 0;
  accept_fd = 0;
  return (unsigned char *)NULL;
}

unsigned char*
IIIMPClient::get_content(char *packet_header, int isConnect) {
#if !defined(USE_FRAMEMGR_ALWAYS)
#else /* USE_FRAMEMGR_ALWAYS */
  extern XimFrameRec im_packet_header_fr[];
  FrameMgr fm;
#endif /* USE_FRAMEMGR_ALWAYS */
  int total_size;
  unsigned char opcode;
  unsigned char length[3];
  unsigned int data_length = 0;

#if !defined(USE_FRAMEMGR_ALWAYS)
  char *ptr;
  ptr = packet_header;
  total_size = 4;
  /* byte swap is not required */
  req_get8(ptr, opcode);
  req_get8(ptr, length[2]);
  req_get8(ptr, length[1]);
  req_get8(ptr, length[0]);
#else /* USE_FRAMEMGR_ALWAYS */
  fm = FrameMgrInit(im_packet_header_fr, (char *)packet_header, need_swap);
  total_size = FrameMgrGetTotalSize(fm);
  /* get data */
  FrameMgrGetToken(fm, opcode);
  FrameMgrGetToken(fm, length[2]);
  FrameMgrGetToken(fm, length[1]);
  FrameMgrGetToken(fm, length[0]);
  /* free FrameMgr */
  FrameMgrFree(fm);
#endif /* USE_FRAMEMGR_ALWAYS */

  /* calculate length */
  data_length  = (length[2] << 16);
  data_length += (length[1] << 8);
  data_length += length[0];

  unsigned char *p = new unsigned char[total_size + data_length * 4];
  unsigned char *pp = p;
  *pp++ = opcode;
  *pp++ = length[2]; *pp++ = length[1]; *pp++ = length[0];

  if (!isConnect) {
    if (data_length > 0) {
      if ((data_length * 4) != read_data((char *)pp, data_length * 4)) {
	goto read_error;
      }
    }
  } else {
    *pp++ = byteOrder;
    const int to_be_read = data_length * 4 - sizeof(char);
    if (to_be_read != read_data((char *)pp, to_be_read)) {
      goto read_error;
    }
  }
  return (unsigned char *)p;
 read_error:
  delete accept_fd;
  im_id = 0;
  accept_fd = 0;
  return (unsigned char *)NULL;
}

unsigned char*
IIIMPClient::get_amessage() {
  IIimpProtoHdr hdr;
  int header_len = sizeof(IIimpProtoHdr);

  if (header_len != read_data((char *)&hdr, header_len)) {
    delete accept_fd;
    im_id = 0;
    accept_fd = 0;
    return (unsigned char *)NULL;
  }
  return get_content((char*)&hdr, False);
}

int
IIIMPClient::Select() {
  struct timeval timeout;

  if (being_deleted) {
    // wait 10 minutes
    timeout.tv_sec  = 600L;
    timeout.tv_usec = 0L;
  } else {
    // wait 1.0 second
    timeout.tv_sec  = 1L;
    timeout.tv_usec = 0L;
  }
  return accept_fd->select_fd(timeout);
}

void
IIIMPClient::dispatch(unsigned char *p, int &flag) {
  IMProtocolStruct call_data;
  IIimpProtoHdr *hdr = (IIimpProtoHdr*)p;
  unsigned char *p1 = (unsigned char *)(hdr + 1);
  if (hdr == (IIimpProtoHdr*)NULL) return;

  memset(&call_data, 0, sizeof(IMProtocolStruct));

  call_data.major_code = hdr->opcode;

  switch (call_data.major_code) {
  case IM_CONNECT:
    connect(&call_data, p1);
    break;
  case IM_DISCONNECT:
    dis_connect(&call_data, p1);
    break;
  case IM_SETIMVALUES:
    set_imvalues(&call_data, p1);
    break;
  case IM_GETIMVALUES:
    get_imvalues(&call_data, p1);
    break;
  case IM_CREATEIC:
    create_ic(&call_data, p1);
    break;
  case IM_SETICVALUES:
    set_icvalues(&call_data, p1);
    break;
  case IM_GETICVALUES:
    get_icvalues(&call_data, p1);
    break;
  case IM_SETICFOCUS:
    set_icfocus(&call_data, p1);
    break;
  case IM_UNSETICFOCUS:
    unset_icfocus(&call_data, p1);
    break;
  case IM_DESTROYIC:
    destroy_ic(&call_data, p1);
    break;
  case IM_RESETIC:
    reset_ic(&call_data, p1);
    break;
  case IM_FORWARD_EVENT:
    forward_event(&call_data, p1);
    break;
  case IM_TRIGGER_NOTIFY:
    trigger_notify(&call_data, p1);
    break;
  case IM_PREEDIT_START_REPLY:
    preedit_start_reply(&call_data, p1);
    break;
  case IM_PREEDIT_CARET_REPLY:
    preedit_caret_reply(&call_data, p1);
    break;
  case IM_AUX_SETVALUES:
    aux_set_values(&call_data, p1);
    break;
  default:
    break;
  }
}
