/* Copyright 2013 Akira Ohta (akohta001@gmail.com)
    This file is part of ntch.

    The ntch 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 3 of the License, or
    (at your option) any later version.

    The ntch is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with ntch.  If not, see <http://www.gnu.org/licenses/>.
    
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#include <assert.h>

#include "utils/nt_std_t.h"
#include "utils/text.h"
#include "_2ch/maru_2ch.h"
#include "net/nt_http.h"

nt_maru_2ch_tp nt_maru_2ch_alloc(char *id, char *pw)
{
	assert(id && pw);

	nt_maru_2ch_tp ptr =
		malloc(sizeof(nt_maru_2ch_t));
	if(!ptr)
		return NULL;
	
	ptr->id = nt_trim(id);
	ptr->pw = nt_trim(pw);
	ptr->sid = NULL;
	return ptr;
}

BOOL get_session_id(nt_maru_2ch_tp marup)
{
	char *url = "https://2chv.tora3.net/futen.cgi";
	char post_data[256];
	char out_buf[1024*4];
	char *referer = "https://2chv.tora3.net/";
	char *user_agent = "DOLIB/1.00";
	nt_link_tp linkp;
	nt_key_value_tp kvp;
	BOOL result = FALSE;
	char *cptr;

	memset(post_data, 0, sizeof(post_data));
	memset(out_buf, 0, sizeof(out_buf));

	if(!marup || !marup->id || !marup->pw)
		return FALSE;

	if(marup->sid){
		free(marup->sid);
		marup->sid = NULL;
	}

	kvp = malloc(sizeof(nt_key_value_t));
	kvp->key = "X-2ch-UA";
	kvp->value = "monaweb/1.00";
	linkp = nt_link_add_data(NULL, kvp);

	sprintf(post_data, "ID=%s&PW=%s",
			marup->id, marup->pw);
	memset(out_buf, 0, sizeof(out_buf));

	if(!nt_http_post(url, post_data, out_buf, sizeof(out_buf),
				referer, user_agent, linkp, NULL)){
		goto ERROR_TRAP;
	}
	cptr = strstr(out_buf, "SESSION-ID=");
	if(cptr){
		cptr += strlen("SESSION-ID=");
		marup->sid = nt_trim(cptr);
		result = TRUE;
	}

ERROR_TRAP:
	free(kvp);
	free(linkp);
	return result;
}


void nt_maru_2ch_free(nt_maru_2ch_tp marup)
{
	if(!marup)
		return;
	if(marup->id)
		free(marup->id);
	if(marup->pw)
		free(marup->pw);
	if(marup->sid)
		free(marup->sid);
	free(marup);
}
