

#import "UICollectionView+YMHelper.h"
#import <objc/runtime.h>

#define         METHOD_NAME_A           @"resumeR"
#define         METHOD_NAME_B           @"eloads"

#define         PROPERTY_NAME_A         @"_reloa"
#define         PROPERTY_NAME_B         @"dingSuspe"
#define         PROPERTY_NAME_C         @"ndedCount"

@implementation UICollectionView (YMHelper)

- (void)registerCellWithReuseIdentifierClass:(nullable Class)cellClass
{
    [self registerClass:cellClass forCellWithReuseIdentifier:NSStringFromClass(cellClass)];
}

- (void)registerNibCellWithReuseIdentifierClass:(nullable Class)cellClass
{
    [self registerNib:[UINib nibWithNibName:NSStringFromClass(cellClass) bundle:nil] forCellWithReuseIdentifier:NSStringFromClass(cellClass)];
}


+ (void)load
{
    NSString *oldMethodString = [NSString stringWithFormat:@"_%@%@", METHOD_NAME_A, METHOD_NAME_B];
    Method oldMethod = class_getInstanceMethod(self, NSSelectorFromString(oldMethodString));
    Method newMethod = class_getInstanceMethod(self, @selector(__zz_resumeReloads));
    method_exchangeImplementations(oldMethod, newMethod);
}

- (void)__zz_resumeReloads {
    [self __zz_resumeReloads];
    NSString *pName = [NSString stringWithFormat:@"%@%@%@", PROPERTY_NAME_A, PROPERTY_NAME_B, PROPERTY_NAME_C];
    NSNumber *number = [self valueForKey:pName];
    if (number.longLongValue < 0) {
        [self setValue:@(0) forKey:pName];
    }
}

- (void)reloadDataNoScroll
{
    CGPoint currentOffset = self.contentOffset;
    CGSize contentSizeBeforeInsert = self.collectionViewLayout.collectionViewContentSize;
    
    [self reloadData];
    
    CGSize contentSizeAfterInsert = self.collectionViewLayout.collectionViewContentSize;
    
    CGFloat deltaHeight = contentSizeAfterInsert.height - contentSizeBeforeInsert.height;
    currentOffset.y += deltaHeight > 0 ? deltaHeight : 0;
    NSLog(@"the currentOffset %f", currentOffset.y);
    [self setContentOffset:currentOffset animated:NO];
}

- (void)reloadDataHorizontalNoScroll
{
    CGPoint currentOffset = self.contentOffset;
    [self reloadData];
    [self setContentOffset:currentOffset animated:NO];
}

@end
