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

#import "ICRQuestionManager.h"
#import "IBTImagePicker.h"
#import "GTOPatrolPlan.h"
#import "GTOQuestion.h"
#import "ICRStoreResult.h"
#import "IBTAudioController.h"
#import "GTOStore.h"
#import "ICRQuestionBaseViewController.h"
//#import "ICRQResultViewController.h"

#import "GTODisplayResult.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>

@interface ICRQuestionManager () <CLLocationManagerDelegate>
@property (weak, nonatomic) UIViewController *m_baseRootViewCtrl;
@property (strong, nonatomic) NSArray *m_arrQuestions;
@property (strong, nonatomic) NSArray *m_arrAnswers;
@property (strong, nonatomic) NSArray *m_arrQuestViewCtrls;
@property (strong, nonatomic) NSDate *m_startTime;

@property (strong, nonatomic) CLLocationManager *m_locationManager;
@property (strong, nonatomic) NSString *m_nsLongtitude;
@property (strong, nonatomic) NSString *m_nsLatitude;

@property (strong, nonatomic) ICRStoreResult *m_result;

@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 - Life Cycle
- (instancetype)init {
    self = [super init];
    if (!self) {
        return nil;
    }
    
    [[IBTAudioController sharedController] setup];
//    [self initLocaltionMgr];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectedProblem) name:KNOTIFICATION_QUESTION_SELECTED object:nil];
    return self;
}

#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_storeResult:(ICRStoreResult *)m_storeResult {
//    if ([_m_storeResult isEqual:m_storeResult]) {
//        if (_openQuestAction) {
//            _openQuestAction();
//            self.openQuestAction = NULL;
//        }
//        return;
//    }
    
    _m_storeResult = m_storeResult;

   
    for(NSDictionary *dictDisplayR in m_storeResult.arrDisplayResults) {
        GTODisplayResult *displayR = [GTODisplayResult DBObject];
        [displayR praseFromJsonDict:dictDisplayR];
        if ([displayR.category isEqualToString:_m_category]) {
            NSMutableArray *muArrQ = [@[]mutableCopy];
            for(NSDictionary *dictQuestion in  displayR.arrQuestions) {
                GTOQuestion *question = [GTOQuestion DBObject];
                [question praseFromJsonDict:dictQuestion];
                [muArrQ addObject:question];
            }
            NSMutableArray *muArrA = [@[]mutableCopy];
            for(NSDictionary *dictAnswer in  displayR.arrAnswers) {
                ICRAnswer *answer = [ICRAnswer DBObject];
                [answer praseFromJsonDict:dictAnswer];
                [muArrA addObject:answer];
            }
            self.m_arrQuestions = muArrQ;
            self.m_arrAnswers = muArrA;
            break;
        }
    }
    
                if (_openQuestAction) {
                    _openQuestAction();
                    self.openQuestAction = NULL;
                }

//    if (!_m_storeResult) {
//        [self cleanQuestions];
//        return;
//    }
//    
//    __block BOOL bIsQComplete = NO;
//    __block BOOL bIsAComplete = NO;
//    
//    NSUInteger uiQuestionsCount = [_m_storeResult.questions count];
//    
//    NSArray *arrQuestIDs = [_m_storeResult.questions valueForKeyPath:@"uuid"];
//    
//    
//    ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
//        NSString * sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@ IN %@  ORDER BY %@ ASC", [GTOQuestion TableName], @"uuid", [IBTModel ValuePlaceholdersWithCount:uiQuestionsCount], @"lineNo"];
//        NSLog(@"%@",sql);
//        return [db executeQuery:sql withArgumentsInArray:arrQuestIDs];
//    };
//    
//    __weak typeof(self)weakSelf = self;
//    ICRDatabaseFetchResultsBlock fetchResultsBlk = ^(NSArray *fetchedObjects) {
//        __strong __typeof(weakSelf)strongSelf = weakSelf;
//        NSMutableArray *categoryQuestions = [NSMutableArray array];
//        
//        for (GTOQuestion *questE in fetchedObjects) {  //符合区域分类的，（其实可以用数据表查询的，但是还没实现？？？？？？）
//            if ([questE.category isEqualToString:_m_category]) {
//                [categoryQuestions addObject:questE];
//            }
//        }
//        strongSelf.m_arrQuestions = categoryQuestions;//fetchedObjects;
//        bIsQComplete = YES;
//        
//        if (bIsAComplete) {
//            if (_openQuestAction) {
//                _openQuestAction();
//                self.openQuestAction = NULL;
//            }
//        }
//    };
//    
//    ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
//    [dbCtrl runFetchForClass:[GTOQuestion class]
//                  fetchBlock:fetchBlk
//           fetchResultsBlock:fetchResultsBlk];
//    
//    // StoreResult
//    ICRDatabaseFetchBlock srFetchBlk = ^FMResultSet *(FMDatabase *db) {
//        __strong __typeof(weakSelf)strongSelf = weakSelf;
////        NSString * sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@ = ? AND %@ = ?", [ICRStoreResult TableName], @"uuid", @"store_uuid"];//根据油站找对应的答案
//        NSString * sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@=? and %@=? and %@=?", [ICRStoreResult TableName], @"uuid", @"store_uuid",@"category"];//根据油站找对应的答案
//        return [db executeQuery:sql,strongSelf.m_patrolPlan.uuid ,strongSelf.m_storeID,strongSelf.m_category];
//    };
//    
//    ICRDatabaseFetchResultsBlock srFetchResultsBlk = ^(NSArray *fetchedObjects) {
//        __strong __typeof(weakSelf)strongSelf = weakSelf;
//        strongSelf.m_result = [fetchedObjects firstObject];
//        
//        NSMutableArray *mArr = [NSMutableArray array];
//        for (NSDictionary *dict in _m_result.answers) {
//            for(GTOQuestion *question in self.m_arrQuestions){
//                if ([dict[@"questionUuid"] isEqualToString:question.uuid]) {
//                    ICRAnswer *answer = [ICRAnswer DBObject]; //：需要加上问题区域的分类
//                    [answer praseFromLocalDict:dict];
//                    answer.bIsAnswered = YES;
//                    
//                    [mArr safeAddObject:answer];
//                }
//            }
//           
//        }
//        
//        
//        strongSelf.m_arrAnswers = [mArr count] > 0 ? mArr : nil;
//        
//        bIsAComplete = YES;
//        
//        if (bIsQComplete) {
//            if (_openQuestAction) {
//                _openQuestAction();
//                strongSelf.openQuestAction = NULL;
//            }
//        }
//    };
//    
//    [dbCtrl runFetchForClass:[ICRStoreResult class]
//                  fetchBlock:srFetchBlk
//           fetchResultsBlock:srFetchResultsBlk];
}

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

}

- (void)initLocaltionMgr {
    if ([CLLocationManager locationServicesEnabled]) {
        
        self.m_locationManager = [[CLLocationManager alloc] init];
        
        _m_locationManager.delegate = self;
        
        _m_locationManager.desiredAccuracy = kCLLocationAccuracyBest; //控制定位精度,越高耗电量越大。
        
        _m_locationManager.distanceFilter = 100; //控制定位服务更新频率。单位是“米”
        
        if ([_m_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
            [_m_locationManager requestAlwaysAuthorization];
        }
    }
}

- (void)fetchLocation {
    [_m_locationManager startUpdatingLocation];
}


- (void)openQuestionVCFromViewControler:(UIViewController *)VC withStoreResult:(ICRStoreResult *)storeResult  {
    if (![VC isKindOfClass:[UIViewController class]] || !storeResult) {
        return;
    }
    
    [self fetchLocation];
    
    self.m_startTime = [NSDate date];
    
    self.m_baseRootViewCtrl = VC;
    
    __weak typeof(self)weakSelf = self;
    void(^block)(void) = ^(void) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSMutableArray *arrViews = [NSMutableArray array];
        NSUInteger uiCount = [_m_arrQuestions count];
        NSUInteger uiIndex = 0;
        NSUInteger uiAIndex = 0;
        for (GTOQuestion *questE in strongSelf.m_arrQuestions) {
            ICRAnswer *answerE = [strongSelf.m_arrAnswers safeObjectAtIndex:uiIndex];//待解决：这里不应该是根据index去找问题对应的答案，应该根据questionuuid   
            ICRQuestionBaseViewController *qVC = [[ICRQuestionBaseViewController alloc] initWithQuestion:questE answer:answerE];
//            qVC.m_plan_uuid = self.m_plan_uuid;
//            qVC.m_store_uuid = self.m_store_uuid;
            qVC.m_storeResult = _m_storeResult;
            qVC.m_uiIndex = uiIndex;
            qVC.title = [NSString stringWithFormat:@"%@(%@/%@)",questE.category ,@( uiIndex + 1 ), @( uiCount )];
            [arrViews addObject:qVC];
            
            
            uiIndex ++;
            
            if (answerE) {
                uiAIndex ++;
            }
        }
        
        for(ICRQuestionBaseViewController *questionBaseVC in arrViews){
            for(ICRAnswer *answer in _m_arrAnswers){
                if ([answer.questionUuid isEqualToString:questionBaseVC.m_question.uuid]) {
                    questionBaseVC.m_answer = answer;
                }
            }
        }
        
        strongSelf.m_arrQuestViewCtrls = [arrViews count] > 0 ? arrViews : nil;
        self.m_maxProblemLineno = uiAIndex + 1;
        
        if (_m_arrQuestViewCtrls) {
            BaseNavigationViewController *navCtrl = [[BaseNavigationViewController alloc] initWithRootViewController:[arrViews firstObject]];
            
            NSArray *VCs = nil;
            if (uiAIndex < [arrViews count]) {
                VCs = [arrViews subarrayWithRange:NSMakeRange(0, uiAIndex + 1)];
            }
            else {

                VCs = [arrViews subarrayWithRange:NSMakeRange(0, uiAIndex )];
            }
            
            navCtrl.viewControllers = VCs;
            self.m_vcs = [NSArray arrayWithArray:VCs];
            
            [VC presentViewController:navCtrl animated:YES completion:NULL];
        }
    };
    
    self.openQuestAction = block;
    
    self.m_storeResult = storeResult;
}
- (void)openQuestionVCFromViewControler:(UIViewController *)VC
                            storeResult:(ICRStoreResult *)storeResult
                              IsNotEdit: (BOOL)isNotEdit
                           ProblemIndex: (NSInteger) problemIndex {
    if (![VC isKindOfClass:[UIViewController class]] || !storeResult) {
        return;
    }
    [self fetchLocation];
    self.m_startTime = [NSDate date];
    self.m_baseRootViewCtrl = VC;
    __weak typeof(self)weakSelf = self;
    void(^block)(void) = ^(void) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSMutableArray *arrViews = [NSMutableArray array];
        NSUInteger uiCount = [_m_arrQuestions count];
        NSUInteger uiIndex = 0;
        NSUInteger uiAIndex = 0;
        for (GTOQuestion *questE in strongSelf.m_arrQuestions) {
            ICRAnswer *answerE = [strongSelf.m_arrAnswers safeObjectAtIndex:uiIndex];//待解决：这里不应该是根据index去找问题对应的答案，应该根据questionuuid
            ICRQuestionBaseViewController *qVC = [[ICRQuestionBaseViewController alloc] initWithQuestion:questE answer:answerE];
            //            qVC.m_plan_uuid = self.m_plan_uuid;
            //            qVC.m_store_uuid = self.m_store_uuid;
            qVC.d_notEdit = isNotEdit;
            qVC.m_storeResult = _m_storeResult;
            qVC.m_uiIndex = uiIndex;
            qVC.title = [NSString stringWithFormat:@"%@(%@/%@)",questE.category ,@( uiIndex + 1 ), @( uiCount )];
            [arrViews addObject:qVC];
            uiIndex ++;
            if (answerE) {
                uiAIndex ++;
            }
        }
        for(ICRQuestionBaseViewController *questionBaseVC in arrViews){
            for(ICRAnswer *answer in _m_arrAnswers){
                if ([answer.questionUuid isEqualToString:questionBaseVC.m_question.uuid]) {
                    questionBaseVC.m_answer = answer;
                }
            }
        }
        strongSelf.m_arrQuestViewCtrls = [arrViews count] > 0 ? arrViews : nil;
        self.m_maxProblemLineno = uiAIndex + 1;
        if (_m_arrQuestViewCtrls) {
            BaseNavigationViewController *navCtrl = [[BaseNavigationViewController alloc] initWithRootViewController:[arrViews firstObject]];
            NSArray *VCs = nil;
            BOOL condition = problemIndex <= uiAIndex && problemIndex > 0;
            if (condition) {
                VCs = [arrViews subarrayWithRange:NSMakeRange(0, problemIndex)];
            } else {
                if (uiAIndex < [arrViews count]) {
                    VCs = [arrViews subarrayWithRange:NSMakeRange(0, uiAIndex + 1)];
                }
                else {
                    
                    VCs = [arrViews subarrayWithRange:NSMakeRange(0, uiAIndex )];
                }
            }
            navCtrl.viewControllers = VCs;
            self.m_vcs = [NSArray arrayWithArray:VCs];
            [VC presentViewController:navCtrl animated:YES completion:NULL];
        }
    };
    self.openQuestAction = block;
    self.m_storeResult = storeResult;

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

#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    CLLocation *currentPosition = [locations lastObject];
    
    self.m_nsLongtitude = [NSString stringWithFormat:@"%.3f",currentPosition.coordinate.longitude];
    self.m_nsLatitude = [NSString stringWithFormat:@"%.3f",currentPosition.coordinate.latitude];
    //_mylocationLongitude
    [_m_locationManager stopUpdatingLocation];
}

@end
