/* 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 <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <signal.h>
#include <ncursesw/ncurses.h>

#include "env.h"
#include "error.h"
#include "nt_string.h"
#include "_2ch/_2ch.h"
#include "utils/nt_std_t.h"
#include "utils/text.h"
#include "ui/disp.h"


int disp_html_result(nt_write_data_handle h_write_data)
{
	FILE *tmp_fp;
	pid_t pid;
	char fname[512];
	char buf[1024*2];
	int len, len2, ret;
	wchar_t *cptr, *sptr, *html_str;
	const wchar_t *result_html;
	size_t sz;
	int result = -1;

	result_html = nt_write_data_get_html_result(h_write_data);
	if(!result_html)
		return -1;
	pid = getpid();

	sprintf(fname, "%s/result%d.tmp", LOG_PATH, pid);
	tmp_fp = fopen(fname, "w");
	if(!tmp_fp)
		return -1;

	
	len = wcslen(result_html);
	html_str = malloc(sizeof(wchar_t)*(len+1));
	if(!html_str){
		fclose(tmp_fp);
		unlink(fname);
		return -1;
	}
	wcscpy(html_str, result_html);
	cptr = wcsstr(html_str, L"書きこみました");
	if(cptr){
		result = 0;
		goto ERROR_TRAP;
	}
	cptr = wcsstr(html_str, L"2ch_X:cookie");
	if(cptr)
		result = 1;
	
	sptr = html_str;
	while(NULL != (cptr = wcsstr(sptr, L"<br>"))){
		*cptr = L'\0';
		sz = wcstombs(buf, sptr, sizeof(buf));
		if(sz < 0){
			fclose(tmp_fp);
			goto ERROR_TRAP;
		}
		if(sz > fwrite(buf, 1, sz, tmp_fp)){
			fclose(tmp_fp);
			goto ERROR_TRAP;
		}
		if(1 > fwrite("\n", 1, 1, tmp_fp)){
			fclose(tmp_fp);
			goto ERROR_TRAP;
		}
		sptr = cptr+4;
	}
	len2 = (html_str + len) - sptr;
	if(len2 > 0){
		sz = wcstombs(buf, sptr, sizeof(buf));
		if(sz < 0){
			fclose(tmp_fp);
			goto ERROR_TRAP;
		}
		if(sz > fwrite(buf, 1, sz, tmp_fp)){
			fclose(tmp_fp);
			goto ERROR_TRAP;
		}
	}

	fclose(tmp_fp);

	sprintf(buf, "%s %s", EDITOR_CMD, fname);
	ret = system(buf);
	if (WIFSIGNALED(ret) &&
         	(WTERMSIG(ret) == SIGINT || 
			 WTERMSIG(ret) == SIGQUIT))
		goto ERROR_TRAP;

ERROR_TRAP:
	free(html_str);
	unlink(fname);
	return result;
}
