#include <stdio.h>
#include "ime_buffer.h"


void free_ime_buffer(ImeBufferRec *ime_buffer)
{
    int i;

    if (ime_buffer) {
        if (ime_buffer->candidates.candidates) {
            for (i = 0; i < ime_buffer->max_cand_num; ++i) {
                if (ime_buffer->candidates.candidates[i].text)
                    free(ime_buffer->candidates.candidates[i].text);
            }
            free(ime_buffer->candidates.candidates);
        }
        if (ime_buffer->candidates.numbers)
            free(ime_buffer->candidates.numbers);
        if (ime_buffer->preedit.preedit.text)
            free(ime_buffer->preedit.preedit.text);
        if (ime_buffer->commit_buf)
            free(ime_buffer->commit_buf);
        free(ime_buffer);
    }
}

ImeBufferRec * alloc_ime_buffer(
    int max_preedit_bytes,
    int max_candidate_num,
    int max_candidate_byte,
    int max_numberring_byte,
    int max_commit_byte)
{
    int i, suc;

    ImeBufferRec *ime_buffer = (ImeBufferRec *)calloc(1, sizeof(ImeBufferRec));
    if (ime_buffer) {

        suc = ((ime_buffer->commit_buf = (unsigned char*)malloc(max_commit_byte)) != NULL);
        suc = suc && ((ime_buffer->preedit.preedit.text = (unsigned char*)calloc(1, max_preedit_bytes)) != NULL);
        suc = suc && ((ime_buffer->candidates.numbers = (unsigned char*)calloc(1, max_numberring_byte*max_candidate_num+1)) != NULL);
        suc = suc && ((ime_buffer->candidates.candidates = (ImeText)calloc(max_candidate_num, sizeof(ImeTextRec))) != NULL);
        if (suc) {
            memset(ime_buffer->candidates.candidates, 0, sizeof(ImeTextRec)*max_candidate_num);
            ime_buffer->max_cand_num = max_candidate_num;
        }
        for (i = 0; suc && i < max_candidate_num; ++i) {
            suc = suc && ((ime_buffer->candidates.candidates[i].text = (unsigned char *)calloc(1, max_candidate_byte)) != NULL);
        }

        if (!suc) {
            free_ime_buffer(ime_buffer);
            ime_buffer = NULL;
        }
    }
    clear_ime_buffer(ime_buffer);
    return ime_buffer;
}

void clear_ime_buffer(ImeBufferRec *ime_buffer)
{
    if (ime_buffer) {
        if (ime_buffer->preedit.preedit.text)
            ime_buffer->preedit.preedit.text[0] = '\0';
        ime_buffer->preedit.caret = 0;
        ime_buffer->candidates.count = 0;
        ime_buffer->return_status = 0;
    }
}
