//
//  ICRAnnouncementDetailViewController.m
//  Cruiser
//
//  Created by Lili Wang on 15/4/15.
//  Copyright (c) 2015年 Xummer. All rights reserved.
//

#import "ICRAnnouncementDetailViewController.h"
#import "ICRAnnouncementDetailContentView.h"
#import "ICRAnnouncement.h"
#import "ICRAttachment.h"
#import "IBTWebViewController.h"

@interface ICRAnnouncementDetailViewController ()
<ICRAnnouncementDetailHeadViewDelegate>


@property (strong, nonatomic) IBTUIScrollView *m_scrollView;
@property (strong, nonatomic) ICRAnnouncementDetailContentView *m_contentView;
@property (strong, nonatomic) ICRAnnouncement *m_announcement;
@property (assign, nonatomic) NSString *m_announcementId;

@end

@implementation ICRAnnouncementDetailViewController

#pragma mark - Life Cycle
- (instancetype)initWithAnnouncementData:(id)announcement {
    self = [super init];
    if (!self) {
        return nil;
    }
    
    if ([announcement isKindOfClass:[ICRAnnouncement class]]) {
        ICRAnnouncement *aAnnouncement = announcement;
        self.m_announcement = aAnnouncement;
        self.m_announcementId =  aAnnouncement.uuid;
    } else {
        self.m_announcementId = announcement;
    }
    
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = [IBTCommon localizableString:@"Announcement Detail"];
    [self initContentView];

    [self registerContentViewForKVO];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self doHttpGetAnnocement];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [self unregisterContentViewFromKVO];
}

#pragma mark - Private Method
- (void)initContentView {
    self.m_scrollView = [[IBTUIScrollView alloc] initWithFrame:self.view.bounds];
    [_m_scrollView autoresizingWithStrechFullSize];
    
    [self.view addSubview:_m_scrollView];
    
    self.m_contentView = [[ICRAnnouncementDetailContentView alloc] initWithFrame:_m_scrollView.bounds];
    _m_contentView.m_delegate = self;
    [_m_contentView updateWithAnnouncement:_m_announcement];
    
    
    [_m_scrollView addSubview:_m_contentView];
    _m_scrollView.contentSize = _m_contentView.size;
}

#pragma mark - Data Update

- (void)fetchAnnouncement {
    ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
        NSString * sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@ = ?", [ICRAnnouncement TableName], @"uuid"];
        return [db executeQuery:sql,  self.m_announcementId];
    };
    
    __weak typeof(self)weakSelf = self;
    ICRDatabaseFetchResultsBlock fetchResultsBlk = ^(NSArray *fetchedObjects) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        strongSelf.m_announcement = [fetchedObjects firstObject];
        [strongSelf.m_contentView updateWithAnnouncement:_m_announcement];
    };
    
//    ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
//    [dbCtrl runFetchForClass:[ICRAnnouncement class]
//                  fetchBlock:fetchBlk
//           fetchResultsBlock:fetchResultsBlk];
}
- (void)fetchAnnouncementWithData: (id)data {
    if ([data[@"success"] integerValue]== 1) {
        NSDictionary *dict = data[@"data"];
        ICRAnnouncement *announcement = [ICRAnnouncement DBObject];
        [announcement praseFromJsonDict:dict];
        announcement.readType = self.m_announcement.readType;
        self.m_announcement = announcement;
        if (_m_announcement.readType ==  kICRAnnouncementTypeUnread) {
            [self doHttpAfficheRead];
        } else if (_m_announcement.readType ==  kICRAnnouncementTypeReaded) {
             [self.m_contentView updateWithAnnouncement:_m_announcement];
        } else {}
    } else {
        
    }
}
- (void)doHttpGetAnnocement {
    __weak typeof(self)weakSelf = self;
    void(^succ)(id) = ^(id data) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf fetchAnnouncementWithData:data];
    };
    
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView showTips:data];
    };
    
  
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    [httpCtrl doGetBoardWithID:self.m_announcementId
                       success:succ
                       failure:fail];
}
- (void)doHttpAfficheRead {
    __weak typeof(self)weakSelf = self;
    void(^succ)(id) = ^(id data) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [self.m_contentView updateWithAnnouncement:_m_announcement];
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        [userDefault setObject:@"true" forKey:READ_SUCCESS];
       // [strongSelf fetchAnnouncement];
    };
    
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView showTips:data];
    };
    
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    [httpCtrl doReadBoardWithID:self.m_announcementId
                        success:succ failure:fail];
}
#pragma mark - KVO

- (void)registerContentViewForKVO {
    for (NSString *keyPath in [self observableKeypaths]) {
        [_m_contentView addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:NULL];
    }
}

- (void)unregisterContentViewFromKVO {
    for (NSString *keyPath in [self observableKeypaths]) {
        [_m_contentView removeObserver:self forKeyPath:keyPath];
    }
}

- (NSArray *)observableKeypaths {
    return @[ @"frame" ];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    _m_scrollView.contentSize = _m_contentView.size;
}

#pragma mark -
- (void)AttachmentDetail:(ICRAttachment *)attach downloadBtn:(UIButton *)button {
   // NSString *attUrl = [ICRHTTPController AttachmentUrlWithID:@( attach.aID )];
    NSString *url = [NSString stringWithFormat:@"%@%@",HTTP_LOCAL_BASE_URL,attach.fileUrl];
    IBTWebViewController *WVC = [[IBTWebViewController alloc] initWithURL:url presentModal:NO extraInfo:nil];
    [self PushViewController:WVC animated:YES];
}

@end
