#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma comment (lib,"ws2_32.lib")
#include<winsock2.h>
#include "irc.h"

int IRCPORT=6667;
int PROXYPORT=8080;
char *PROXYHOST="127.0.0.1";
IRC_t *ircini(char *nick,char *host,char *channel,char *pass)
{
	IRC_t *session;
	session=(IRC_t *)calloc(sizeof(IRC_t),1);
	strcpy(session->nick,nick);
	strcpy(session->host,host);
	strcpy(session->channel,channel);
    strcpy(session->pass,pass);
	return session;
}
int ircopen(IRC_t *session)
{
	struct sockaddr_in addr;
	int err=0;
	int length=0;
	char buffer[500];
	WSADATA wsadata; 
	addr.sin_family=AF_INET; 
	addr.sin_port=htons(PROXYPORT);
	if( WSAStartup( MAKEWORD(2,2),&wsadata )!=0 )
    {
        return -1;
    }
	session->socket=socket(AF_INET,SOCK_STREAM,0);
	if(session->socket==INVALID_SOCKET) 
	{
	    WSACleanup();
	    return -2;
	}
	addr.sin_addr.S_un.S_addr=inet_addr(PROXYHOST);
	err=connect(session->socket,(SOCKADDR *)&addr,sizeof(addr));
	if(err==SOCKET_ERROR)
	{
	    WSACleanup();
		return -3;
	}
    length=sprintf(buffer,"CONNECT %s:%d HTTP/1.0\n\n",session->host,IRCPORT);
	send(session->socket,buffer,length,0);
	return 0;
}
int irclogin(IRC_t *session)
{
	char buffer[512];
	int length=0;
	if(session->pass[0]!=0)
	{
		length=sprintf(buffer,"PASS %s\r\n",session->pass);
	    send(session->socket,buffer,length,0);
	}
	length=sprintf(buffer,"NICK %s\r\n",session->nick);
	send(session->socket,buffer,length,0);
	length=sprintf(buffer,"USER %s 127.0.0.1 %s %s\r\n",session->nick,session->host,session->nick);
	send(session->socket,buffer,length,0);
	length=sprintf(buffer,"JOIN %s\r\n",session->channel);
	send(session->socket,buffer,length,0);
	return 0;
}

int ircgetline(IRC_t *session)
{
	char ch;
	int status=0,length=0;
	char buffer[512];
	session->length=0;
	while(1)
	{
		status=recv(session->socket,&ch,1,0);
		if(status!=1)
		{
			status=0;
			break;
		}
		else if(ch!='\r')
		{
			if(length<510)
			{
			    session->line[length]=ch;
			    length++;
			    session->line[length]=0;
			}
			else
			{
				status=2;
				break;
			}

		}
		else
		{
			status=3;
			break;
		}
	}
	switch(status)
	{
	
	case 0:
		session->status=-1;
		strcpy(session->errormsg,"Connection closed\n");
		session->length=length;
		break;
	case 2:
		session->length=length;
		session->status=-1;
		strcpy(session->errormsg,"message length limit exceeded\n");
		break;
    case 3:
		recv(session->socket,&ch,1,0);
		if(ch!='\n')
		{
			session->status=-1;
			strcpy(session->errormsg,"No \\n found\n");
			break;
		}
		else session->status=0;
		session->length=length;
		break;
	}
	if(!strncmp(session->line,"PING ",5)||!strncmp(session->line,"ping ",5))
	{
		length=sprintf(buffer,"PONG %s\r\n",&(session->line[5]));
		send(session->socket,buffer,length,0);
		session->status=1;
	}

	return session->status;
}