 
//
//  KLTStartUp.m
//  KaiLiTe
//
//  Created by yuwell on 2025/3/25.
//  Copyright © 2025 boosal. All rights reserved.
//
 
#import "KLTStartUp.h"
#import "KLTDatabaseHandler.h"
#import "KLTBluetoothManager.h"
 
@implementation KLTStartUp
 
+ (KLTStartUp *)shared {
    static KLTStartUp *shared = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shared = [[KLTStartUp alloc] init];
    });
    return shared;
}
 
- (instancetype)init {
    self = [super init];
    if (self) {
    }
    return self;
}
 
#pragma mark - 初始化
 
- (void)setup {
 
    NSLog(@"KLTStartUp setup begin");
 
   
 
    [self handleAlgorithmException];
 
    NSLog(@"KLTStartUp setup finished");
}
 
#pragma mark - 处理算法异常数据 (ErrorCode = 2)
 
- (void)handleAlgorithmException {
 
    Device *currentDevice = KLTBluetoothManager.sharedManager.currentDevice;
 
    if (!currentDevice) {
        NSLog(@"KLTStartUp: currentDevice is nil");
        return;
    }
 
    if (currentDevice.identifier.length == 0 ||
        currentDevice.initialBeginDate.length == 0) {
 
        NSLog(@"KLTStartUp: device session invalid");
        return;
    }
 
    NSLog(@"KLTStartUp: start algorithm recovery for device %@", currentDevice.identifier);
 
    /*
     Step 1
     Delete corrupted ReceiveData starting from first errorCode = 2
     */
    [[KLTDatabaseHandler shared] handleReceiveDataForError2Data];
 
    /*
     Step 2
     Rebuild algorithm history
     */
    [[KLTDatabaseHandler shared] reloadQueryHistoryData:NO];
 
    NSLog(@"KLTStartUp: algorithm recovery completed");
}
 
@end