1/*
2 * Copyright 2014-2015 Haiku, Inc. All rights reserved.
3 * Distributed under the terms of the MIT License.
4 *
5 * Authors:
6 *		Adrien Destugues, pulkomandy@pulkomandy.tk
7 *		John Scipione, jscipione@gmail.com
8 */
9
10#include <unicode/uversion.h>
11#include <StringFormat.h>
12
13#include <Autolock.h>
14#include <FormattingConventionsPrivate.h>
15#include <LanguagePrivate.h>
16
17#include <ICUWrapper.h>
18
19#include <unicode/msgfmt.h>
20
21
22BStringFormat::BStringFormat(const BLanguage& language, const BString pattern)
23	: BFormat(language, BFormattingConventions())
24{
25	_Initialize(UnicodeString::fromUTF8(pattern.String()));
26}
27
28
29BStringFormat::BStringFormat(const BString pattern)
30	: BFormat()
31{
32	_Initialize(UnicodeString::fromUTF8(pattern.String()));
33}
34
35
36BStringFormat::~BStringFormat()
37{
38	delete fFormatter;
39}
40
41
42status_t
43BStringFormat::InitCheck()
44{
45	return fInitStatus;
46}
47
48
49status_t
50BStringFormat::Format(BString& output, const int64 arg) const
51{
52	if (fInitStatus != B_OK)
53		return fInitStatus;
54
55	UnicodeString buffer;
56	UErrorCode error = U_ZERO_ERROR;
57
58	Formattable arguments[] = {
59		(int64)arg
60	};
61
62	FieldPosition pos;
63	buffer = fFormatter->format(arguments, 1, buffer, pos, error);
64	if (!U_SUCCESS(error))
65		return B_ERROR;
66
67	BStringByteSink byteSink(&output);
68	buffer.toUTF8(byteSink);
69
70	return B_OK;
71}
72
73
74status_t
75BStringFormat::_Initialize(const UnicodeString& pattern)
76{
77	fInitStatus = B_OK;
78	UErrorCode error = U_ZERO_ERROR;
79	Locale* icuLocale
80		= BLanguage::Private(&fLanguage).ICULocale();
81
82	fFormatter = new MessageFormat(pattern, *icuLocale, error);
83
84	if (fFormatter == NULL)
85		fInitStatus = B_NO_MEMORY;
86
87	if (!U_SUCCESS(error)) {
88		delete fFormatter;
89		fInitStatus = B_ERROR;
90		fFormatter = NULL;
91	}
92
93	return fInitStatus;
94}
95