//
//  ReferenceManager.m
//  react-native-bt-device
//
//  Created by Ran Zhao on 9/2/24.
//

#import "ReferenceManager.h"

@implementation ReferenceManager

- (instancetype)init {
    self = [super init];
    if (self) {
        self.refList = [NSMutableArray array];
        self.curReference = nil;
        self.mCurrentReference = nil;
        self.kCount = -1;
    }
    return self;
}

- (Reference *)getRefValue {
    return self.curReference;
}

- (void)addCurrentReference:(double)value index:(NSInteger)index {
    self.mCurrentReference = [[Reference alloc] initWithValue:value index:index];
}

- (void)addReference:(double)value time:(NSDate *)time {
    Reference *ref = [[Reference alloc] initWithValue:value time:time];
    if (![self isExist:ref]) {
        [self.refList addObject:ref];
    }
    [self.refList sortUsingComparator:^NSComparisonResult(Reference *lhs, Reference *rhs) {
        return [lhs.time compare:rhs.time];
    }];
}

- (BOOL)isExist:(Reference *)bgRef {
    for (Reference *bg in self.refList) {
        if ([bg.time timeIntervalSince1970] == [bgRef.time timeIntervalSince1970]) {
            return YES;
        }
    }
    return NO;
}

- (BOOL)isCalK {
    return self.kCount == 0;
}

- (BOOL)isWaitCalK {
    return self.kCount == 2 || self.kCount == 1;
}

- (Reference *)findReferenceByDate:(NSDate *)curTime {
    for (Reference *d in self.refList) {
        double interval = ([curTime timeIntervalSince1970] - [d.time timeIntervalSince1970]) / 60.0;
        if (interval <= 0.0) {
            self.kCount -= 1;
            return nil;
        }
        if (interval <= 3.0) {
            self.kCount = 2;
            self.curReference = d;
            return d;
        }
    }
    self.kCount -= 1;
    return nil;
}

- (Reference *)findReferenceByIndex:(NSInteger)index {
    double interval = (index - self.mCurrentReference.index) * 3;
    if (interval < 0.0) {
        self.kCount -= 1;
        return nil;
    }
    if (interval <= 3.0) {
        self.kCount = 2;
        self.curReference = self.mCurrentReference;
        return self.mCurrentReference;
    }
    self.kCount -= 1;
    return nil;
}

+ (NSDate *)stringToDate:(NSString *)dateStr {
    NSString *formatStr = @"yyyy/MM/dd HH:mm:ss";
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:formatStr];
    NSDate *date = [formatter dateFromString:dateStr];
    return date;
}

@end
