//
//  ICRQuestionManager.m
//  Cruiser
//
//  Created by Xummer on 15/6/2.
//  Copyright (c) 2015年 Xummer. All rights reserved.
//

#import "ICRQuestionManager.h"
#import "IBTImagePicker.h"
#import "ICRPatrolPlan.h"
#import "ICRQuestion.h"

#import "ICRQuestionBaseViewController.h"

@interface ICRQuestionManager ()
@property (weak, nonatomic) UIViewController *m_baseRootViewCtrl;
@property (strong, nonatomic) NSArray *m_arrQuestions;
@property (strong, nonatomic) NSArray *m_arrQuestViewCtrls;

@property (copy, nonatomic) void(^openQuestAction)();

@end

@implementation ICRQuestionManager

#pragma mark - Class Method
+ (instancetype)sharedManager {
    static ICRQuestionManager *_sharedManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedManager = [[[self class] alloc] init];
    });
    
    return _sharedManager;
}

#pragma mark - Getter
- (IBTImagePicker *)m_imagePicker {
    if (!_m_imagePicker) {
        self.m_imagePicker = [[IBTImagePicker alloc] init];
    }
    
    return _m_imagePicker;
}

#pragma mark - Setter
- (void)setM_bIsHelpViewAttachHide:(BOOL)bIsHelpViewAttachHide {
    _m_bIsHelpViewAttachHide = bIsHelpViewAttachHide;
    
    for (ICRQuestionBaseViewController *qVC in _m_arrQuestViewCtrls) {
        [qVC.m_helperView updateViewRect:bIsHelpViewAttachHide];
    }
}

- (void)setM_patrolPlan:(ICRPatrolPlan *)patrolPlan {
    if ([_m_patrolPlan isEqual:patrolPlan]) {
        if (_openQuestAction) {
            _openQuestAction();
            self.openQuestAction = NULL;
        }
        return;
    }
    
    _m_patrolPlan = patrolPlan;
    
    if (!_m_patrolPlan) {
        [self cleanQuestions];
        return;
    }
    
    NSUInteger uiQuestionsCount = [_m_patrolPlan.questions count];
    
    NSArray *arrQuestIDs = [_m_patrolPlan.questions valueForKeyPath:@"uuid"];
    
    ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
        NSString * sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@ IN %@ ORDER BY %@ ASC", [ICRQuestion TableName], @"uuid", [IBTModel ValuePlaceholdersWithCount:uiQuestionsCount], @"lineNo"];
        return [db executeQuery:sql withArgumentsInArray:arrQuestIDs];
    };
    
    __weak typeof(self)weakSelf = self;
    ICRDatabaseFetchResultsBlock fetchResultsBlk = ^(NSArray *fetchedObjects) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        
        strongSelf.m_arrQuestions = fetchedObjects;
        if (_openQuestAction) {
            _openQuestAction();
            self.openQuestAction = NULL;
        }
    };
    
    ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
    [dbCtrl runFetchForClass:[ICRQuestion class]
                  fetchBlock:fetchBlk
           fetchResultsBlock:fetchResultsBlk];
}

#pragma mark - Private Method
- (void)cleanQuestions {
    self.m_imagePicker = nil;
    self.m_arrQuestions = nil;
    self.m_arrQuestViewCtrls = nil;
    self.m_baseRootViewCtrl = nil;
}

#pragma mark - Public Method
- (void)openQuestionVCFromViewControler:(UIViewController *)VC withPlan:(ICRPatrolPlan *)plan  {
    if (![VC isKindOfClass:[UIViewController class]] || !plan) {
        return;
    }
    self.m_baseRootViewCtrl = VC;
    void(^block)(void) = ^(void) {
        NSMutableArray *arrViews = [NSMutableArray array];
        NSUInteger uiCount = [_m_arrQuestions count];
        NSUInteger uiIndex = 0;
        for (ICRQuestion *questE in self.m_arrQuestions) {
            ICRQuestionBaseViewController *qVC = [[ICRQuestionBaseViewController alloc] initWithQuestion:questE];
            qVC.m_uiIndex = uiIndex;
            qVC.title = [NSString stringWithFormat:@"巡店纪录(%@/%@)", @( uiIndex + 1 ), @( uiCount )];
            [arrViews addObject:qVC];
            uiIndex ++;
        }
        self.m_arrQuestViewCtrls = [arrViews count] > 0 ? arrViews : nil;
        
        if (_m_arrQuestViewCtrls) {
            IBTUINavigationController *navCtrl = [[IBTUINavigationController alloc] initWithRootViewController:[arrViews firstObject]];
            navCtrl.viewControllers = arrViews;
            [VC presentViewController:navCtrl animated:YES completion:NULL];
        }
    };
    self.openQuestAction = block;
    self.m_patrolPlan = plan;
}

- (UIViewController *)questionViewControlAtIndex:(NSUInteger)uiIndex {
    if (uiIndex < [_m_arrQuestViewCtrls count]) {
        return _m_arrQuestViewCtrls[ uiIndex ];
    }
    else {
        return nil;
    }
}

@end
