/* 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 <string.h>
#include <unistd.h>
#include <ncursesw/ncurses.h>
#include <locale.h>
#include <iconv.h>
#include <assert.h>

#include "ui/disp_string.h"



int nt_add_wch(WINDOW *w, const wchar_t wc, attr_t attr)
{
	cchar_t	c;

	/*
	 * This will supress valgrind's verbose messages.
	 */
	memset(&c, '\0', sizeof(cchar_t));

	c.attr	=	attr;
	c.chars[0]	=	wc;
	c.chars[1]	=	L'\0';
	return	wadd_wch(w, &c);
}


int nt_add_wstr(WINDOW *w, const wchar_t *wc, attr_t attr)
{
	int ret;
	assert(wc);
	wattr_on(w, attr, NULL);
	ret = waddwstr(w, wc);
	wattr_off(w, attr, NULL);
	return ret;
}

int nt_add_wnch(WINDOW *w, const wchar_t wc, attr_t attr, size_t colmns)
{
	int i, delta;
	cchar_t c;
	/*
	 * This will supress valgrind's verbose messages.
	 */
	memset(&c, '\0', sizeof(cchar_t));
	c.attr = attr;
	c.chars[0] = wc;
	c.chars[1] = L'\0';
	if(wc < 128)
		delta = 1;
	else
		delta = 2;
	colmns /= 2;
	colmns *= 2;
	for(i = 0; i < colmns; i+=delta){
		if(ERR == wadd_wch(w, &c))
			break;
	}
	return i / delta;
}

int nt_add_wnstr(WINDOW *w, const wchar_t *wc, attr_t attr, size_t colmns)
{
	int i, col, len;
	cchar_t c;
	assert(wc);
	/*
	 * This will supress valgrind's verbose messages.
	 */
	memset(&c, '\0', sizeof(cchar_t));

	col = 0;
	c.attr = attr;
	c.chars[1] = L'\0';
	len = wcslen(wc);
	for(i = 0; i < len && col < colmns; i++){
		if(wc[i] <= 128 || 
				(wc[i] >= 0xff66 && wc[i] <= 0xff9d)){
			col++;
		}else{
			col += 2;
			if(col >= colmns)
				break;
		}
		c.chars[0] = wc[i];
		if(ERR == wadd_wch(w, &c))
			break;
	}
	return i;
}

int nt_get_column_length(const wchar_t *wc)
{
	int i, column, len;
	wchar_t ch;

	assert(wc);

	len = wcslen(wc);
	column = 0;
	for(i = 0; i < len; i++){
		ch = wc[i];
		if(ch <= 128 || (ch >= 0xff66 && ch <= 0xff9d))
			column++;
		else
			column += 2;
	}
	return column;
}


int nt_get_wc_count_within_colmns(const wchar_t *wc, size_t colmns)
{
	int len;
	int col = 0;
	int i;
	wchar_t ch;
	assert(wc);
	len = wcslen(wc);
	for(i = 0; i < len; i++){
		ch = wc[i];
		if(ch <= 128 || (ch >= 0xff66 && ch <= 0xff9d))
			col++;
		else
			col += 2;
		if(col > colmns)
			return i;
	}
	return i;
}
