1//
2//  SwordBibleBook.m
3//  MacSword2
4//
5//  Created by Manfred Bergmann on 18.02.09.
6//  Copyright 2009 __MyCompanyName__. All rights reserved.
7//
8
9#import "SwordBibleBook.h"
10#import "SwordBibleChapter.h"
11
12
13@implementation SwordBibleBook
14
15@synthesize number;
16@synthesize numberInTestament;
17@synthesize testament;
18@synthesize localizedName;
19@dynamic chapters;
20
21- (id)init {
22    self = [super init];
23    if(self) {
24        self.number = 0;
25        self.numberInTestament = 0;
26        self.testament = 0;
27        self.localizedName = @"";
28        self.chapters = nil;
29    }
30
31    return self;
32}
33
34- (id)initWithBook:(sword::VersificationMgr::Book *)aBook {
35    self = [self init];
36    if(self) {
37        swBook = aBook;
38
39        sword::VerseKey vk = sword::VerseKey(aBook->getOSISName());
40        [self setTestament:vk.getTestament()];
41        [self setNumberInTestament:vk.getBook()];
42
43        // get system localeMgr to be able to translate the english bookName
44        sword::LocaleMgr *lmgr = sword::LocaleMgr::getSystemLocaleMgr();
45        const char *translated = lmgr->translate(swBook->getLongName());
46        self.localizedName = [NSString stringWithUTF8String:translated];
47
48        // in case we don't have ICU support this still works.
49        if(self.localizedName == nil) {
50            self.localizedName = [NSString stringWithCString:translated encoding:NSISOLatin1StringEncoding];
51        }
52        if(self.localizedName == nil) {
53            DLog(@"Unable to get this bookname: %s", translated);
54        }
55    }
56
57    return self;
58}
59
60
61- (void)dealloc {
62    [self setChapters:nil];
63    [self setLocalizedName:nil];
64}
65
66- (NSString *)name {
67    return [NSString stringWithUTF8String:swBook->getLongName()];
68}
69
70- (NSString *)osisName {
71    return [NSString stringWithUTF8String:swBook->getOSISName()];
72}
73
74- (int)numberOfChapters {
75    return swBook->getChapterMax();
76}
77
78- (int)numberOfVersesForChapter:(int)chapter {
79    return swBook->getVerseMax(chapter);
80}
81
82- (void)setChapters:(NSArray *)anArray {
83    chapters = anArray;
84}
85
86- (NSArray *)chapters {
87    if(chapters == nil) {
88        NSMutableArray *temp = [NSMutableArray array];
89        for(int i = 0;i < swBook->getChapterMax();i++) {
90            [temp addObject:[[SwordBibleChapter alloc] initWithBook:self andChapter:i+1]];
91        }
92        [self setChapters:[NSArray arrayWithArray:temp]];
93    }
94    return chapters;
95}
96
97/**
98 get book index for verseKey
99 that is: book number + testament * 100
100 */
101- (int)generatedIndex {
102    return number + testament * 100;
103}
104
105- (sword::VersificationMgr::Book *)book {
106    return swBook;
107}
108
109/** we implement this for sorting */
110- (NSComparisonResult)compare:(SwordBibleBook *)b {
111    return [@(number) compare:@([b number])];
112}
113
114@end
115