1/*
2   Project: MPDCon
3
4   Copyright (C) 2012 Free Software Foundation
5
6   Author: Sebastian Reitenbach
7
8   Created: 2012-11-11 11:11:38 +0100 by sebastia
9
10   This application is free software; you can redistribute it and/or
11   modify it under the terms of the GNU General Public
12   License as published by the Free Software Foundation; either
13   version 2 of the License, or (at your option) any later version.
14
15   This application is distributed in the hope that it will be useful,
16   but WITHOUT ANY WARRANTY; without even the implied warranty of
17   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18   Library General Public License for more details.
19
20   You should have received a copy of the GNU General Public
21   License along with this library; if not, write to the Free
22   Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA.
23*/
24
25#import "SQLiteAdaptor.h"
26
27static NSString* SongRatingStorageDirectory = nil;
28
29@interface SQLiteAdaptor(Private)
30-(NSString *)_getMPDConDBName;
31@end
32
33@implementation SQLiteAdaptor(Private)
34-(NSString *)_getMPDConDBName
35{
36  if (SongRatingStorageDirectory == nil)
37    {
38      NSFileManager* manager;
39      BOOL isDir, exists;
40      NSString *storagePath;
41
42      storagePath = [NSSearchPathForDirectoriesInDomains
43		(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
44      storagePath = [storagePath stringByAppendingPathComponent:
45		[[NSProcessInfo processInfo] processName]];
46      storagePath = [NSString stringWithFormat:@"%@", storagePath];
47      ASSIGN(SongRatingStorageDirectory, storagePath);
48
49      manager = [NSFileManager defaultManager];
50      exists = [manager fileExistsAtPath: SongRatingStorageDirectory
51		isDirectory: &isDir];
52      if (exists)
53	{
54	  if (isDir == NO)
55	    {
56	      [[NSException exceptionWithName:
57			@"SongRatingStorageDirectoryIsNotADirectory"
58				       reason:
59			@"The storage directory for song ratings is not a directory."
60				     userInfo: nil] raise];
61	    }
62	}
63      else
64	{
65	  if ([manager createDirectoryAtPath: SongRatingStorageDirectory
66				  attributes: nil] == NO)
67	    {
68	      [[NSException exceptionWithName:
69			@"SongRatingsStorageDirectoryCreationFailed"
70				       reason:
71			@"Creation of the storage directory for song ratings failed."
72				     userInfo: nil] raise];
73	    }
74	}
75    }
76  return [NSString stringWithFormat:@"%@/MPDCon.sqlite3", SongRatingStorageDirectory];
77}
78@end
79
80@implementation SQLiteAdaptor
81+ (id) sharedSQLiteAdaptor
82{
83  static SQLiteAdaptor *_sharedSQLiteAdaptor = nil;
84
85  if (! _sharedSQLiteAdaptor)
86    {
87      _sharedSQLiteAdaptor = [[SQLiteAdaptor allocWithZone: [self zone]] init];
88    }
89  return _sharedSQLiteAdaptor;
90}
91
92- (id) init
93{
94  NSUserDefaults *defs;
95
96  defs = [NSUserDefaults standardUserDefaults];
97  [defs registerDefaults:
98    [NSDictionary dictionaryWithObjectsAndKeys:
99      [NSDictionary dictionaryWithObjectsAndKeys:
100        [NSDictionary dictionaryWithObjectsAndKeys:
101          [self _getMPDConDBName], @"Database",
102          @"", @"User",
103          @"", @"Password",
104          @"SQLite", @"ServerType",
105          nil],
106        @"MPDCon",
107        nil],
108      @"SQLClientReferences",
109      nil]
110  ];
111  MPDConDB = [[SQLClient clientWithConfiguration: nil name: @"MPDCon"] retain];
112  //[MPDConDB setDurationLogging: 0];
113  [MPDConDB execute: @"CREATE TABLE IF NOT EXISTS SongRatings ( "
114                @"fileName CHAR(1024) PRIMARY KEY, "
115                @"rating INTEGER)",
116                nil];
117  [MPDConDB execute: @"CREATE TABLE IF NOT EXISTS SongLyrics ( "
118                @"fileName CHAR(1024) PRIMARY KEY, "
119                @"lyricsText CHAR(1024), ",
120                @"lyricsURL CHAR(1024) )",
121                nil];
122
123  return self;
124}
125
126- (void) dealloc
127{
128  [MPDConDB disconnect];
129  [MPDConDB release];
130  [super dealloc];
131}
132
133- (void) setRating: (NSInteger) rating forFile: (NSString *) fileName
134{
135  NSString *query;
136
137  query = [NSString stringWithFormat:@"INSERT OR REPLACE INTO \
138		SongRatings(fileName, rating) values(%@, %"PRIiPTR")",
139		[MPDConDB quoteString:fileName], rating];
140  [MPDConDB execute: query, nil];
141}
142- (NSInteger) getRatingForFile: (NSString *) fileName
143{
144  NSString *query;
145  NSMutableArray *records;
146  SQLRecord      *record;
147  NSInteger rating = 0;
148
149  query = [NSString stringWithFormat:@"SELECT rating FROM SongRatings WHERE fileName=%@",
150		[MPDConDB quoteString:fileName]];
151  records = [MPDConDB query: query, nil];
152
153  // we search for the primary key, so we should find exactly one
154  if ([records count] == 1)
155    {
156      record = [records objectAtIndex:0];
157      rating = [[record objectAtIndex:0] integerValue];
158    }
159  return rating;
160}
161- (NSArray *) getFilesForRatingsInRange: (NSRange) range
162{
163  NSArray * ratingsArray;
164
165  ratingsArray = [[NSArray alloc] init];
166
167  return AUTORELEASE(ratingsArray);
168}
169
170- (void) setLyrics: (NSString *) lyricsText withURL: (NSString *) lyricsURL forFile: (NSString *) fileName
171{
172  NSString *query;
173
174  query = [NSString stringWithFormat:@"INSERT OR REPLACE INTO \
175		SongLyrics(fileName, lyricsText, lyricsURL) values(%@, %@, %@)",
176		[MPDConDB quoteString: fileName],
177		[MPDConDB quoteString: lyricsText],
178		[MPDConDB quoteString: lyricsURL]];
179
180  [MPDConDB execute: query, nil];
181}
182- (NSDictionary *) getLyricsForFile: (NSString *) fileName
183{
184  NSString  *query;
185  NSMutableArray *records;
186  SQLRecord *record;
187  NSString *lyricsText, *lyricsURL;
188  NSDictionary *result = nil;
189
190  query = [NSString stringWithFormat:@"SELECT lyricsText, lyricsURL FROM SongLyrics \
191					WHERE fileName=%@", [MPDConDB quoteString: fileName]];
192
193  records = [MPDConDB query: query, nil];
194
195  // we search for the primary key, so we should find exactly one
196  if ([records count] == 1)
197    {
198      record = [records objectAtIndex:0];
199      lyricsText = [record objectAtIndex:0];
200      lyricsURL = [record objectAtIndex:1];
201      result = [NSDictionary dictionaryWithObjectsAndKeys: lyricsText, @"lyricsText",
202		lyricsURL, @"lyricsURL", nil];
203    }
204  return result;
205}
206@end
207