/***************************************************************************
                          tcp.cpp  -  description
                             -------------------
    begin                : Sat Dec 6 2003
    copyright            : (C) 2003 by Wei Zheng
    email                : v_zheng@yahoo.com
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include "tcp.h"

tcp::tcp(){
  memset(mesg,0,sizeof(mesg));
  memset(tmpline,0,sizeof(tmpline));
  memset(finline,0,sizeof(finline));
  counter = 0;
  if(sem_init(&bin_sem, 0, 0)!= 0)
    perror("Semaphore initialization failed");
}
tcp::~tcp(){
}

int tcp::send_mesg(char * ready_mesg, int len)
{
	int mimelen,mesglen;
  char mime[128];
	char head[56];
	int headlen;

	memset(mime,'\0',sizeof(mime));
  strcat(mime,"MIME-Version: 1.0\r\nContent-Type: text/plain; charset=UTF-8\r\nX-MMS-IM-Format:FN=Clean;EF=;CO=000000;CS=0;PF=22\r\n\r\n");
  mimelen = strlen(mime);
  mesglen = mimelen + len;

	memset(head,'\0',sizeof(head));
	sprintf(head,"MSG %d A %d\r\n",counter++,mesglen);
	headlen = strlen(head);

	if(full_write(head,headlen)==-1) return -1;
  if(full_write(mime,mimelen)==-1) return -1;
  if(full_write(ready_mesg,len)==-1) return -1;
	return 0;
}

/** No descriptions */
int tcp::reci_mesg(int length){

  int tmplen;
  int ismesg;

  tmplen=0;
  ismesg=0;
  while(1)
  {
    memset(tmpline,'0',sizeof(tmpline));
    while(get_line(fd,tmpline,sizeof(tmpline))!=0);
    if(strstr(tmpline,"Content-Type: text/plain")!=NULL)
      ismesg = 1;
    tmplen = tmplen + strlen(tmpline) + 2;
    if(strlen(tmpline)==0)
      break;
  }

  if(tmplen!=length)
  {
    memset(tmpline,0,sizeof(tmpline));
    full_read(tmpline,length - tmplen);
  }
  debug("<<< %s\n",tmpline);
  return ismesg;
}

