//
//  ICContactBackupController.m
//  superCleaner
//
//  Created by GY.Z on 2020/7/4.
//  Copyright © 2020 Mazy. All rights reserved.
//

#import "ICContactBackupController.h"
#import "ICContactsTool.h"
#import "ICContactsBackupCell.h"
#import "ICContactsBackupHeader.h"
#import "ICContactsBackup.h"
#import "ICContactsBackupSubController.h"

static NSString * const ICContactsBackupCellID = @"ICContactsBackupCellID";

@interface ICContactBackupController ()<UITableViewDataSource, UITableViewDelegate,ICContactsToolDelegate>

@property (strong, nonatomic) UIButton *backupButton;
@property (nonatomic, strong) UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,strong)UIButton *deleteButton;
@property(nonatomic,strong)ICContactsTool *tools;


@end

@implementation ICContactBackupController
-(NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self setupUI];
}

-(void)setupUI
{
    self.navigationItem.title = ICLocalized(@"BackupContact");
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:ICLocalized(@"ChooseAll") style:UIBarButtonItemStyleDone target:self action:@selector(chooseAction)];

    self.tableView = [[UITableView alloc] initWithFrame: self.view.bounds style: UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 50;
    self.tableView.tableFooterView = [[UIView alloc] init];
//    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"ICContactsBackupCell" bundle:nil] forCellReuseIdentifier:ICContactsBackupCellID];
        
    self.deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.deleteButton setTitle:ICLocalized(@"BackupImmediately") forState:UIControlStateNormal];
    [self.deleteButton setBackgroundImage:[UIImage imageNamed:@"global_green_btn_bg"] forState:UIControlStateNormal];
    [self.deleteButton addTarget:self action:@selector(backupAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.deleteButton];
    self.deleteButton.hidden = NO;
    [self.deleteButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(@(-40));
        make.height.equalTo(@62);
        make.width.equalTo(@343);
    }];
    
    ICContactsBackupHeader *header = [[ICContactsBackupHeader alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 110)];
    [self.tableView setTableHeaderView:header];
    
    self.tools = [ICContactsTool shareInstance];
    self.tools.delegate = self;
    [self.tools loadiCloudDirectory];
    
   
}

-(void)chooseAction
{
    NSString *name = self.navigationItem.rightBarButtonItem.title;
    BOOL choose;
    if ([name isEqualToString:ICLocalized(@"ChooseAll")]) {
        self.navigationItem.rightBarButtonItem.title = ICLocalized(@"CancelAll");
        choose = YES;
    }else{
        self.navigationItem.rightBarButtonItem.title = ICLocalized(@"ChooseAll");
        choose = NO;
    }
    
    for (ICContactsBackup *model in self.dataArray) {
        model.choose = choose;
    }

    [self queryChooseContact];

    [self.tableView reloadData];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 50;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ICContactsBackupCell *cell = [tableView dequeueReusableCellWithIdentifier:ICContactsBackupCellID forIndexPath:indexPath];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    if (self.dataArray.count) {
        ICContactsBackup *model = self.dataArray[indexPath.row];
        cell.model = model;
        
        [cell.button addTarget:self action:@selector(cellChooseAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return cell;
}

-(void)cellChooseAction:(UIButton *)sender
{
    ICContactsBackupCell *cell = (ICContactsBackupCell *)sender.superview.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
//    NSLog(@"点击的是第%ld = row",indexPath.row);
    ICContactsBackup *model = self.dataArray[indexPath.row];
    model.choose = !model.choose;
    
    [self queryChooseContact];
    
    [self.tableView reloadData];
}

-(void)queryChooseContact
{
    [self.deleteButton setTitle:ICLocalized(@"BackupImmediately") forState:UIControlStateNormal];
    for (ICContactsBackup *model in self.dataArray) {
        if (model.choose) {
            [self.deleteButton setTitle:ICLocalized(@"DeleteSelected") forState:UIControlStateNormal];
            break;
        }
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [MobClick event:@"contact_backup_file_click"];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ICContactsBackup *model = self.dataArray[indexPath.row];
    [self.tools getiCloudContactsPath:model.kMDItemURL];
}

/// Delegate
-(void)getiCloudContactsMethods:(NSData *)obj fileInfo:(nonnull NSDictionary *)fileInfo
{
//    NSLog(@"fileInfo = %@",fileInfo);
    NSArray *arr = [NSKeyedUnarchiver unarchiveObjectWithData:obj];
//    NSLog(@"contacts = %@",arr);
    ICContactsBackupSubController *vc = [ICContactsBackupSubController new];
    vc.contacts = arr;
    [self.navigationController pushViewController:vc animated:YES];
    
}

-(void)getiCloudList:(NSArray *)lists
{
    NSLog(@"lists = %@",lists);
    if (lists.count == 0){
        [self.deleteButton setTitle:ICLocalized(@"BackupImmediately") forState:UIControlStateNormal];
    }
    [self.dataArray removeAllObjects];
    NSMutableArray *temp =@[].mutableCopy;
    for (NSDictionary *dict in lists) {
        ICContactsBackup *model = [ICContactsBackup new];
        [model setValuesForKeysWithDictionary:dict];
        NSString *name = dict[@"kMDItemFSName"];
        if ([name containsString:@"Contacts-"]) {
            NSArray *arr = [name componentsSeparatedByString:@"-"];
            if (arr.count > 1) {
                model.timestamp = arr[1];
            }else{
                model.timestamp = @"0";
            }
        }
        [temp addObject:model];
    }
    
    /// 按时间排序
    NSArray *dataArr = [temp sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        ICContactsBackup *model1 = (ICContactsBackup *)obj1;
        ICContactsBackup *model2 = (ICContactsBackup *)obj2;
        
        if ([model1.timestamp integerValue] < [model2.timestamp integerValue]) {
            return NSOrderedDescending;
        }else if ([model1.timestamp integerValue] > [model2.timestamp integerValue]){
            return NSOrderedAscending;
        }
        return NSOrderedSame;
    }];
    
    [self.dataArray addObjectsFromArray:dataArr];
    

    [self.tableView reloadData];
}

- (void)backupAction:(UIButton *)sender {
    NSString *name = self.deleteButton.titleLabel.text;
    if ([name isEqualToString:ICLocalized(@"BackupImmediately")]) {
        [MobClick event:@"contact_backup_now"];
        NSLog(@"立即备份");
        ICContactsTool *tools = [ICContactsTool shareInstance];
        NSString *time = [tools getNowTimeTimestamp];
        [tools synciCloudContactsFileName:time];
    }else{
        NSLog(@"删除所选");
        [MobClick event:@"contact_backup_file_delete"];
        if (self.dataArray.count == 0) return;
        
        for (ICContactsBackup *model in self.dataArray) {
            if (model.choose) {
                [self.tools deleteiCloudContactsUrlFile:model.kMDItemURL];
            }
        }
    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tools loadiCloudDirectory];
    });
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    });
   
}

-(NSString *)getRandomStr
{
    char data[6];
    for (int x=0;x < 6;data[x++] = (char)('A' + (arc4random_uniform(26))));
    NSString *randomStr = [[NSString alloc] initWithBytes:data length:6 encoding:NSUTF8StringEncoding];
    NSString *string = [NSString stringWithFormat:@"%@",randomStr];
    
    return string;

}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
