Source

headstak / StakItem.m

Full commit
//
//  StakItem.m
//  headstak
//
//  Created by Veghead on 3/11/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "StakItem.h"
#import "StakItemView.h"
#import "StakDB.h"

@implementation StakItem
@synthesize view = _view,
            description = _description,
            pushTime = _pushTime,
            popTime = _popTime,
            itemType = _itemType,
            db = _db,
            itemId = _itemId;

- (id)initNewItemOfType:(NSUInteger)type InDb:(StakDB *)db {
    self = [super init];
    if (self) {
        _db = db;
        _view = nil;
        NSDate *now = [NSDate date];
        _pushTime = now;
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setTimeStyle:NSDateFormatterNoStyle];
        [formatter setDateStyle:NSDateFormatterMediumStyle];
        NSString *dateDesc = [NSDateFormatter localizedStringFromDate:_pushTime 
         dateStyle:NSDateFormatterMediumStyle
         timeStyle:NSDateFormatterMediumStyle];
        
        _itemType = type;
        NSString *itemTypeString = [db typeNameForId:_itemType];
        _description = [NSString stringWithFormat:@"%@ - %@\n", itemTypeString, dateDesc];
        
        [db executeUpdate:@"INSERT INTO stakitems\
         (pushdate, description, itemtype)\
         values (?,?,?)",now, _description, 
         [NSNumber numberWithInteger:_itemType]];
        
        _itemId = [[self db] lastInsertRowId];
    }
    return self;

}

- (id)initWithDictionary:(NSDictionary *)dict inDb:(StakDB *)db {
    self = [super init];
    if (self) {
        _view = nil;
        _db = db;
        _pushTime = [dict objectForKey:@"pushdate"];
        _popTime = [dict objectForKey:@"popdate"];
        _itemType = [[dict objectForKey:@"itemtype"] integerValue];
        _description = [dict objectForKey:@"description"];
        _itemId = [[dict objectForKey:@"id"] integerValue];
    }
    return self;
}

/**
  * @brief get the view associated with this item
  */
- (StakItemView *)viewInStakView:(StakView *)stakView {
    if ([self view]) return [self view];
    [self setView:[[StakItemView alloc] initWithStakItem:self inStakView:stakView]];
    return [self view];
}

/**
  * @brief write the item back to the database
  */
- (void)save {
    [[self db] executeUpdate:@"UPDATE stakitems SET \
     pushdate = ?, popdate = ?, description = ?, itemtype = ? \
     WHERE id = ?", [self pushTime], [self popTime], [self description], 
     [NSNumber numberWithInt:[self itemType]], [NSNumber numberWithInt:[self itemId]]];
}
@end