//
//  ICRSyncViewController.m
//  XFFruit
//
//  Created by Xummer on 3/24/15.
//  Copyright (c) 2015 Xummer. All rights reserved.
//

#import "ICRSyncViewController.h"
#import "IBTTableView.h"
#import "IBTTableViewCell.h"
#import "ICRSyncCellContentView.h"
#import "ICRPostTask.h"
#import "ICRAnswer.h"
#import "ICRStoreResult.h"

#define TABLE_HEAD_VIEW_HEIGHT       (50)
#define TITLE_LABEL_LEFT_MARGIN      (10)
#define TITLE_LABEL_VERTICAL_MARGIN  (20)

static NSString *syncCellIdetifier = @"IBTTableViewCell";

@interface ICRSyncViewController ()
<
UITableViewDataSource,
UITableViewDelegate
>

@property (strong, nonatomic) IBTTableView *m_tableView;
@property (strong, nonatomic) UIButton *m_SyncButton;
@property (strong, nonatomic) NSArray *m_arrFunctionTitle;
@property (strong, nonatomic) NSArray *m_arrTasks;
@property (strong, nonatomic) NSArray *m_arrPatrolResults;

@end

#pragma mark - life style

@implementation ICRSyncViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupSubviews];
    [self initData];
    [self getUnuploadData];

    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Privite Method
- (void)setupSubviews {
    
    self.m_tableView = [[IBTTableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    [_m_tableView registerClass:[IBTTableViewCell class] forCellReuseIdentifier:syncCellIdetifier];
    _m_tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    _m_tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _m_tableView.delegate = self;
    _m_tableView.dataSource = self;
    [self.view addSubview:_m_tableView];
    
    CGRect frame = self.view.frame;
    frame.size.height = TABLE_HEAD_VIEW_HEIGHT;
    
    UIView *headView = [[UIView alloc] initWithFrame:frame];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:(CGRect){
        .origin.x = TITLE_LABEL_LEFT_MARGIN,
        .origin.y = TITLE_LABEL_VERTICAL_MARGIN,
        .size.width = headView.width - TITLE_LABEL_LEFT_MARGIN * 2,
        .size.height = 20
    }];
    titleLabel.text = [IBTCommon localizableString:@"To Upload Data"];
    titleLabel.font = [UIFont systemFontOfSize:15];
    [headView addSubview:titleLabel];
    
    _m_tableView.tableHeaderView = headView;
    
    UIButton *button = nil;
    UIView *tableFooter = [_m_tableView buttonViewWithTitle:[IBTCommon localizableString:@"Submit"]
                                                      color:ICR_ORANGE_BTN_COLOR
                                                     topGap:20
                                                    pointer:&button
                                                     target:self
                                                     action:@selector(onSubmitAction:)];
    _m_tableView.tableFooterView = tableFooter;
    self.m_SyncButton = button;
}

- (void)initData {
    self.m_arrFunctionTitle = @[[IBTCommon localizableString:@"Task Progressing"],
                                [IBTCommon localizableString:@"Patrol Result"],
                                [IBTCommon localizableString:@"SignIn Record"]];
}

- (void)getUnuploadData {
    
    ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];

    __weak typeof(self)weakSelf = self;
    
    // Task
    ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
        NSString * sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@ = ?", [ICRPostTask TableName], @"isNotUploaded"];
        return [db executeQuery:sql,  @( YES )];
    };
    
    ICRDatabaseFetchResultsBlock fetchResultsBlk = ^(NSArray *fetchedObjects) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        strongSelf.m_arrTasks = fetchedObjects;
        [strongSelf.m_tableView reloadData];
    };
    
    [dbCtrl runFetchForClass:[ICRPostTask class]
                  fetchBlock:fetchBlk
           fetchResultsBlock:fetchResultsBlk];
    
    // Patrol
    ICRDatabaseFetchBlock pfetchBlk = ^FMResultSet *(FMDatabase *db) {
        NSString * sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@ = ?", [ICRStoreResult TableName], @"isNotUploaded"];
        return [db executeQuery:sql,  @( YES )];
    };
    
    ICRDatabaseFetchResultsBlock pfetchResultsBlk = ^(NSArray *fetchedObjects) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        strongSelf.m_arrPatrolResults = fetchedObjects;
        [strongSelf.m_tableView reloadData];
    };
    
    [dbCtrl runFetchForClass:[ICRStoreResult class]
                  fetchBlock:pfetchBlk
           fetchResultsBlock:pfetchResultsBlk];
}

#pragma mark - Actions

- (void)onSubmitAction:(id)sender {
    
    NSUInteger uiTasksCount = [_m_arrTasks count];
    NSUInteger uiResultCount = [_m_arrPatrolResults count];
    
    if (uiTasksCount == 0 &&
        uiResultCount == 0) {
        return;
    }
    
    __block NSUInteger uiTaskComleteCount = 0;
    __block NSUInteger uiResultComleteCount = 0;
    
    __weak typeof(self)weakSelf = self;
    void(^taskComplete)(void) = ^(void) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        uiTaskComleteCount ++;
        
        if (uiTaskComleteCount == uiTasksCount &&
            uiResultComleteCount == uiResultCount) {
            [strongSelf getUnuploadData];
        }
    };
    
    void(^patrolComplete)(void) = ^(void) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;

        uiResultComleteCount ++;
        
        if (uiTaskComleteCount == uiTasksCount &&
            uiResultComleteCount == uiResultCount) {
            [strongSelf getUnuploadData];
        }
    };
    
    for (ICRPostTask * task in _m_arrTasks) {
        [self updateTask:task complete:taskComplete];
    }
    
    for (ICRStoreResult * result in _m_arrPatrolResults) {
        [self updateResult:result complete:patrolComplete];
    }
}

#pragma mark - UITableViewDatasource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:syncCellIdetifier];
    cell.userInteractionEnabled = NO;
    [self configueCell:cell forRowAtIndexPath:indexPath];
    
    return cell;
}

- (void)configueCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    IBTTableViewCell *mCell = (IBTTableViewCell *)cell;
    UIView *view = mCell.contentView;
    
    ICRSyncCellContentView *contentView = [view viewWithClass:[ICRSyncCellContentView class]];
    
    if (!contentView) {
        
        contentView = [[ICRSyncCellContentView alloc] initWithFrame:view.bounds];
        [view addSubview:contentView];
        
    }
    
    NSUInteger uiCount = 0;
    switch (indexPath.row) {
        case 0:
            uiCount = [_m_arrTasks count];
            break;
        case 1:
            uiCount = [_m_arrPatrolResults count];
            break;
            
        default:
            break;
    }
    
    [contentView updateItemLabelTitle:[_m_arrFunctionTitle objectAtIndex:indexPath.row]
                       valueLabelText:@( uiCount )];
    
}

#pragma mark - Action

- (void)uploadTaskAndAttaches:(ICRStoreResult *)result complete:(void (^)(void))complete {
    
    ICRStoreResult *res = result;
    
    NSMutableArray *mArr = [NSMutableArray array];
    NSMutableArray *mArrAns = [NSMutableArray array];
    for (NSDictionary *dict in res.answers) {
        ICRAnswer *ans = [ICRAnswer DBObject];
        [ans praseFromLocalDict:dict];
        [mArr safeAddObject:ans];
        [mArrAns safeAddObject:[ans dictForCommit]];
    }
    
    res.answers = mArrAns;
    
    NSMutableArray *arrTasks = [NSMutableArray array];
    NSMutableArray *arrAttachs = [NSMutableArray array];
    
    // Answers
    for (ICRAnswer *answer in mArr) {
        if (answer.task) {
            ICRPostTask *postTask = [ICRPostTask DBObject];
            [postTask praseFromLocalDict:answer.task];
            
//            [arrAttachs safeAddObject:postTask.photo];
            
            [arrTasks safeAddObject:[postTask dictForCommit]];
        }
        
        [arrAttachs safeAddObject:answer.photo];
        [arrAttachs safeAddObject:answer.voice];
    }
    
    if ([arrAttachs count] == 0 && [arrTasks count] == 0) {
        if (complete) {
            complete();
        }
        
        return;
    }
    
    __block NSUInteger uiTaskCompleteCount = 0;
    __block NSUInteger uiAttachCompleteCount = 0;
    NSUInteger uiAllTaskCount = [arrTasks count];
    NSUInteger uiAllAttachCount = [arrAttachs count];
    
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    
    void(^taskSucc)(id) = ^(id data) {
        uiTaskCompleteCount ++;
        
        if (uiTaskCompleteCount == uiAllTaskCount &&
            uiAttachCompleteCount == uiAllAttachCount)
        {
            if (complete) {
                complete();
            }
        }
    };
    
    void(^taskFail)(id) = ^(id data) {
        uiTaskCompleteCount ++;
        
        if (uiTaskCompleteCount == uiAllTaskCount &&
            uiAttachCompleteCount == uiAllAttachCount)
        {
            if (complete) {
                complete();
            }
        }
    };
    
    void(^attSucc)(id) = ^(id data) {
        uiAttachCompleteCount ++;
        
        if (uiTaskCompleteCount == uiAllTaskCount &&
            uiAttachCompleteCount == uiAllAttachCount)
        {
            if (complete) {
                complete();
            }
        }
    };
    
    void(^attFail)(id) = ^(id data) {
        uiAttachCompleteCount ++;
        
        if (uiTaskCompleteCount == uiAllTaskCount &&
            uiAttachCompleteCount == uiAllAttachCount)
        {
            if (complete) {
                complete();
            }
        }
    };
    
    for (NSDictionary *dict in arrTasks) {
        [httpCtrl doCreateNewTaskWithInfo:dict success:taskSucc failure:taskFail];
    }
    
    for (NSDictionary *dict in arrAttachs) {
        [httpCtrl doAddAttachment:dict success:attSucc failure:attFail];
    }
}


- (void)updateResult:(ICRStoreResult *)result complete:(void (^)(void))complete {
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    
    __weak typeof(self)weakSelf = self;
    void(^succ)(id) = ^(id data) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf uploadTaskAndAttaches:result complete:complete];
    };
    
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView showTips:data];
//        result.isNotUploaded = YES;
        
        [result saveToDBWithHandleData:NULL complete:complete fail:NULL];
    };
    
    [httpCtrl doAnswerPatrolPlanWithID:result.uuid infoData:[result dictForCommit]
                               success:succ
                               failure:fail];

}

- (void)doUploadAttachmentsToTask:(ICRPostTask *)task
                         complete:(void (^)(void))complete
{
//    if (!task.photo) {
//        if (complete) {
//            complete();
//        }
//        return;
//    }
//    
    void(^suc)(id) = ^(id data) {
        if (complete) {
            complete();
        }
    };
    
    void(^fai)(id) = ^(id data) {
//        [IBTLoadingView showTips:@"上传失败"];
    };
    
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
//    
//    [httpCtrl doAddAttachment:task.photo
//                      success:suc
//                      failure:fai];
}


- (void)updateTask:(ICRPostTask *)task complete:(void (^)(void))complete {
    __weak typeof(self)weakSelf = self;
    
    void(^succ)(id) = ^(id data) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf doUploadAttachmentsToTask:task complete:complete];
    };
    
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView showTips:data];
//        task.isNotUploaded = YES;
        
        [task saveToDBWithHandleData:NULL complete:complete fail:NULL];
    };
    
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    [httpCtrl doCreateNewTaskWithInfo:[task dictForCommit] success:succ failure:fail];

}
@end
