//
//  RouteCollectionViewLayout.m
//  NaviDemo
//
//  Created by linbiao on 2019/5/15.
//  Copyright © 2019年 Baidu. All rights reserved.
//

#import "RouteCollectionViewLayout.h"
#import "MapCommonDefine.h"

@interface RouteDecorationSpliterView : UICollectionReusableView

@property (nonatomic, readonly) UIView *line;

@end

@implementation RouteDecorationSpliterView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        _line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, 0.5)];
        _line.backgroundColor = UIColorFromRGB(0xeaeaea);
        _line.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        [self addSubview:_line];
        
        _line.userInteractionEnabled = NO;
    }
    
    return self;
}

@end


NSString * const kRouteDecorationSpliterKind = @"kRouteLineKind";
NSString * const kRouteSupplementaryIconKind = @"kRouteSectionIconKind";
NSString * const kRouteSupplementaryLineKind = @"kRouteSupplementaryLineKind";
NSString * const kRouteSupplementaryFooterKind = @"kRouteSupplementaryFooterKind";

@interface RouteCollectionViewLayout ()
{
    
}

@end

@implementation RouteCollectionViewLayout

- (instancetype)init {
    if (self = [super init]) {
        [self registerClass:[RouteDecorationSpliterView class] forDecorationViewOfKind:kRouteDecorationSpliterKind];
    }
    return self;
}

static float spliterRightOffset = 15;
+ (void)setSpliterRightOffset:(float)offset {
    spliterRightOffset = offset;
}

- (void)prepareLayout {
    const CGFloat iconCenterX = _leftPanelWidth / 2;
    
    _rightPanelWidth = self.collectionView.bounds.size.width - _leftPanelWidth;
    _cellWidth = _rightPanelWidth - self.contentInsets.right;
    
    NSMutableDictionary *iconInfomation = [NSMutableDictionary dictionary];
    NSMutableDictionary *cellInfomation = [NSMutableDictionary dictionary];
    NSMutableDictionary *lineInfomation = [NSMutableDictionary dictionary];
    NSMutableDictionary *spliterInfomation = [NSMutableDictionary dictionary];
    
    NSMutableDictionary *layoutInfomation = [NSMutableDictionary dictionary];
    [layoutInfomation setObject:iconInfomation forKey:kRouteSupplementaryIconKind];
    [layoutInfomation setObject:spliterInfomation forKey:kRouteDecorationSpliterKind];
    
    [layoutInfomation setObject:cellInfomation forKey:@"MyCell"];
    [layoutInfomation setObject:lineInfomation forKey:kRouteSupplementaryLineKind];
    
    CGFloat top = self.contentInsets.top; //top for section
    
    NSInteger numberOfSections = [self.collectionView numberOfSections];
    
    NSMutableArray *icons = [NSMutableArray arrayWithCapacity:numberOfSections];
    
    UICollectionViewLayoutAttributes *attr = nil;
    CGSize size = CGSizeZero;
    NSIndexPath *indexPath = nil;
    for (NSInteger i = 0; i < numberOfSections; ++i) {
        NSInteger numberOfCells = [self.collectionView numberOfItemsInSection:i];
        
        
        CGFloat sectionHeight = 0;
        
        for (NSInteger j = 0; j < numberOfCells; ++j) {
            indexPath = [NSIndexPath indexPathForItem:j inSection:i];
            
            size = [self sizeForCellAtIndexPath:indexPath];
            if (size.height > 0) {
                //                if (i !=0)
                { //第一行不要线
                    //cell spliter
                    attr = [UICollectionViewLayoutAttributes layoutAttributesForDecorationViewOfKind:kRouteDecorationSpliterKind withIndexPath:indexPath];
                    int width = 0;
                    if (self.contentInsets.right > 0) {
                        width = _cellWidth;
                    } else {
                        width = _cellWidth - 10;
                    }
                    attr.frame = CGRectMake(_leftPanelWidth + 12, top+size.height, width - spliterRightOffset, 1);
                    attr.zIndex = 1;
                    if (i != numberOfSections-1) {
                        [spliterInfomation setObject:attr forKey:indexPath];
                    }
                }
                
                //cell
                attr = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
                attr.frame = CGRectMake(_leftPanelWidth, top, size.width, size.height);
                [cellInfomation setObject:attr forKey:indexPath];
                
                sectionHeight += size.height;
            }
            
            
            //            if (j == 0)
            { //每个section第一个item添加一个icon
                CGSize iconSize = [self sizeForIconAtIndexPath:indexPath];
                if (iconSize.width && iconSize.height) {
                    CGFloat iconCenterY = top;
                    iconCenterY += size.height /2 - 5;
                    
                    //supplementary icon
                    attr = [UICollectionViewLayoutAttributes layoutAttributesForSupplementaryViewOfKind:kRouteSupplementaryIconKind withIndexPath:indexPath];
                    attr.size = iconSize;
                    attr.center = CGPointMake(iconCenterX, iconCenterY);
                    attr.zIndex = 2;
                    [iconInfomation setObject:attr forKey:indexPath];
                    
                    [icons addObject:attr];
                    NSLog(@"icon attr size is %@, center %@",NSStringFromCGSize(attr.size),NSStringFromCGPoint(attr.center));
                }
            }// if j==0
            
            top += size.height;
        }
        //        top += sectionHeight;
    }
    
    // last icon
    NSIndexPath *lastIndexPath = indexPath;
    CGSize lastSize = size;
    
    if (indexPath.item > 0 && lastSize.height > 0) {
        attr = [UICollectionViewLayoutAttributes layoutAttributesForSupplementaryViewOfKind:kRouteSupplementaryIconKind withIndexPath:lastIndexPath];
        attr.size = [self sizeForIconAtIndexPath:lastIndexPath];
        attr.center = CGPointMake(iconCenterX, top - lastSize.height/2);
        attr.zIndex = 2;
        [iconInfomation setObject:attr forKey:lastIndexPath];
        
        [icons addObject:attr];
    }
    
    // line
    UICollectionViewLayoutAttributes *iconAttr = [icons firstObject];
    for (int i=1; i<icons.count; ++i) {
        UICollectionViewLayoutAttributes *iconAttr2 = [icons objectAtIndex:i];
        
        CGFloat lineHeight = CGRectGetMinY(iconAttr2.frame) - CGRectGetMaxY(iconAttr.frame) - self.linePadding*2;
        
        if (lineHeight > 0) {
            attr = [UICollectionViewLayoutAttributes layoutAttributesForSupplementaryViewOfKind:kRouteSupplementaryLineKind withIndexPath:iconAttr.indexPath];
            
            attr.size = CGSizeMake(self.lineWidth, lineHeight);
            attr.center = CGPointMake(iconAttr.center.x ,
                                      CGRectGetMaxY(iconAttr.frame) + self.linePadding + lineHeight/2);
            attr.zIndex = 1;
            [lineInfomation setObject:attr forKey:iconAttr.indexPath];
        }
        
        iconAttr = iconAttr2;
    }
    
    top += self.contentInsets.bottom;
    
    //footer
    CGSize footerSize = [self sizeForFooter];
    if (footerSize.width && footerSize.height) {
        attr = [UICollectionViewLayoutAttributes layoutAttributesForSupplementaryViewOfKind:kRouteSupplementaryFooterKind withIndexPath:lastIndexPath];
        attr.frame = CGRectMake(0, top, footerSize.width, footerSize.height);
        if (lastIndexPath) {
            NSDictionary *footerInfomation = [NSDictionary dictionaryWithObject:attr forKey:lastIndexPath];
            [layoutInfomation setObject:footerInfomation forKey:kRouteSupplementaryFooterKind];
        }
        
        top += footerSize.height;
    }
    
    
    self.layoutInfomation = layoutInfomation;
    
    _contentSize = CGSizeMake(self.collectionView.bounds.size.width,
                              top);
}

- (CGSize)sizeForCellAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.delegate respondsToSelector:@selector(routeCollectionViewLayout:heightForItemAtIndexPath:)]) {
        CGFloat height = [self.delegate routeCollectionViewLayout:self heightForItemAtIndexPath:indexPath];
        
        return CGSizeMake(_cellWidth, height);
    }
    
    return CGSizeZero;
}

- (CGSize)sizeForIconAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.delegate respondsToSelector:@selector(routeCollectionViewLayout:sizeForIconAtIndexPath:)]) {
        CGSize size = [self.delegate routeCollectionViewLayout:self sizeForIconAtIndexPath:indexPath];
        return size;
    }
    
    return self.supplementaryIconSize;
}

- (CGSize)sizeForFooter {
    if ([self.delegate respondsToSelector:@selector(heightForFooterInRouteCollectionViewLayout:)]) {
        CGFloat height = [self.delegate heightForFooterInRouteCollectionViewLayout:self];
        return CGSizeMake(self.collectionView.width, height);
    }
    
    return CGSizeZero;
}

- (CGSize)collectionViewContentSize {
    return _contentSize;
}

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:self.layoutInfomation.count];
    for (NSString *kind in self.layoutInfomation) {
        NSDictionary *info = [self.layoutInfomation objectForKey:kind];
        
        for (NSString *key in info) {
            UICollectionViewLayoutAttributes *attr = [info objectForKey:key];
            if (CGRectIntersectsRect(rect, attr.frame)) {
                [array addObject:attr];
            }
        }
    }
    
    return array;
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    return self.layoutInfomation[@"MyCell"][indexPath];
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForSupplementaryViewOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath {
    return self.layoutInfomation[elementKind][indexPath];
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForDecorationViewOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath {
    return self.layoutInfomation[elementKind][indexPath];
}

@end
