//
//  YSMASConstraintMaker.m
//  Masonry
//
//  Created by Jonas Budelmann on 20/07/13.
//  Copyright (c) 2013 cloudling. All rights reserved.
//

#import "YSMASConstraintMaker.h"
#import "YSMASViewConstraint.h"
#import "YSMASCompositeConstraint.h"
#import "YSMASConstraint+Private.h"
#import "YSMASViewAttribute.h"
#import "View+YSMASAdditions.h"

@interface YSMASConstraintMaker () <YSMASConstraintDelegate>

@property (nonatomic, weak) YSMAS_VIEW *view;
@property (nonatomic, strong) NSMutableArray *constraints;

@end

@implementation YSMASConstraintMaker

- (id)initWithView:(YSMAS_VIEW *)view {
    self = [super init];
    if (!self) return nil;
    
    self.view = view;
    self.constraints = NSMutableArray.new;
    
    return self;
}

- (NSArray *)install {
    if (self.removeExisting) {
        NSArray *installedConstraints = [YSMASViewConstraint installedConstraintsForView:self.view];
        for (YSMASConstraint *constraint in installedConstraints) {
            [constraint uninstall];
        }
    }
    NSArray *constraints = self.constraints.copy;
    for (YSMASConstraint *constraint in constraints) {
        constraint.updateExisting = self.updateExisting;
        [constraint install];
    }
    [self.constraints removeAllObjects];
    return constraints;
}

#pragma mark - YSMASConstraintDelegate

- (void)constraint:(YSMASConstraint *)constraint shouldBeReplacedWithConstraint:(YSMASConstraint *)replacementConstraint {
    NSUInteger index = [self.constraints indexOfObject:constraint];
    NSAssert(index != NSNotFound, @"Could not find constraint %@", constraint);
    [self.constraints replaceObjectAtIndex:index withObject:replacementConstraint];
}

- (YSMASConstraint *)constraint:(YSMASConstraint *)constraint addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute {
    YSMASViewAttribute *viewAttribute = [[YSMASViewAttribute alloc] initWithView:self.view layoutAttribute:layoutAttribute];
    YSMASViewConstraint *newConstraint = [[YSMASViewConstraint alloc] initWithFirstViewAttribute:viewAttribute];
    if ([constraint isKindOfClass:YSMASViewConstraint.class]) {
        //replace with composite constraint
        NSArray *children = @[constraint, newConstraint];
        YSMASCompositeConstraint *compositeConstraint = [[YSMASCompositeConstraint alloc] initWithChildren:children];
        compositeConstraint.delegate = self;
        [self constraint:constraint shouldBeReplacedWithConstraint:compositeConstraint];
        return compositeConstraint;
    }
    if (!constraint) {
        newConstraint.delegate = self;
        [self.constraints addObject:newConstraint];
    }
    return newConstraint;
}

- (YSMASConstraint *)addConstraintWithAttributes:(YSMASAttribute)attrs {
    __unused YSMASAttribute anyAttribute = (YSMASAttributeLeft | YSMASAttributeRight | YSMASAttributeTop | YSMASAttributeBottom | YSMASAttributeLeading
                                          | YSMASAttributeTrailing | YSMASAttributeWidth | YSMASAttributeHeight | YSMASAttributeCenterX
                                          | YSMASAttributeCenterY | YSMASAttributeBaseline
#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100)
                                          | YSMASAttributeFirstBaseline | YSMASAttributeLastBaseline
#endif
#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000)
                                          | YSMASAttributeLeftMargin | YSMASAttributeRightMargin | YSMASAttributeTopMargin | YSMASAttributeBottomMargin
                                          | YSMASAttributeLeadingMargin | YSMASAttributeTrailingMargin | YSMASAttributeCenterXWithinMargins
                                          | YSMASAttributeCenterYWithinMargins
#endif
                                          );
    
    NSAssert((attrs & anyAttribute) != 0, @"You didn't pass any attribute to make.attributes(...)");
    
    NSMutableArray *attributes = [NSMutableArray array];
    
    if (attrs & YSMASAttributeLeft) [attributes addObject:self.view.ysmas_left];
    if (attrs & YSMASAttributeRight) [attributes addObject:self.view.ysmas_right];
    if (attrs & YSMASAttributeTop) [attributes addObject:self.view.ysmas_top];
    if (attrs & YSMASAttributeBottom) [attributes addObject:self.view.ysmas_bottom];
    if (attrs & YSMASAttributeLeading) [attributes addObject:self.view.ysmas_leading];
    if (attrs & YSMASAttributeTrailing) [attributes addObject:self.view.ysmas_trailing];
    if (attrs & YSMASAttributeWidth) [attributes addObject:self.view.ysmas_width];
    if (attrs & YSMASAttributeHeight) [attributes addObject:self.view.ysmas_height];
    if (attrs & YSMASAttributeCenterX) [attributes addObject:self.view.ysmas_centerX];
    if (attrs & YSMASAttributeCenterY) [attributes addObject:self.view.ysmas_centerY];
    if (attrs & YSMASAttributeBaseline) [attributes addObject:self.view.ysmas_baseline];
    
#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100)
    
    if (attrs & YSMASAttributeFirstBaseline) [attributes addObject:self.view.ysmas_firstBaseline];
    if (attrs & YSMASAttributeLastBaseline) [attributes addObject:self.view.ysmas_lastBaseline];
    
#endif
    
#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000)
    
    if (attrs & YSMASAttributeLeftMargin) [attributes addObject:self.view.ysmas_leftMargin];
    if (attrs & YSMASAttributeRightMargin) [attributes addObject:self.view.ysmas_rightMargin];
    if (attrs & YSMASAttributeTopMargin) [attributes addObject:self.view.ysmas_topMargin];
    if (attrs & YSMASAttributeBottomMargin) [attributes addObject:self.view.ysmas_bottomMargin];
    if (attrs & YSMASAttributeLeadingMargin) [attributes addObject:self.view.ysmas_leadingMargin];
    if (attrs & YSMASAttributeTrailingMargin) [attributes addObject:self.view.ysmas_trailingMargin];
    if (attrs & YSMASAttributeCenterXWithinMargins) [attributes addObject:self.view.ysmas_centerXWithinMargins];
    if (attrs & YSMASAttributeCenterYWithinMargins) [attributes addObject:self.view.ysmas_centerYWithinMargins];
    
#endif
    
    NSMutableArray *children = [NSMutableArray arrayWithCapacity:attributes.count];
    
    for (YSMASViewAttribute *a in attributes) {
        [children addObject:[[YSMASViewConstraint alloc] initWithFirstViewAttribute:a]];
    }
    
    YSMASCompositeConstraint *constraint = [[YSMASCompositeConstraint alloc] initWithChildren:children];
    constraint.delegate = self;
    [self.constraints addObject:constraint];
    return constraint;
}

#pragma mark - standard Attributes

- (YSMASConstraint *)addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute {
    return [self constraint:nil addConstraintWithLayoutAttribute:layoutAttribute];
}

- (YSMASConstraint *)left {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeft];
}

- (YSMASConstraint *)top {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTop];
}

- (YSMASConstraint *)right {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeRight];
}

- (YSMASConstraint *)bottom {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBottom];
}

- (YSMASConstraint *)leading {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeading];
}

- (YSMASConstraint *)trailing {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTrailing];
}

- (YSMASConstraint *)width {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeWidth];
}

- (YSMASConstraint *)height {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeHeight];
}

- (YSMASConstraint *)centerX {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterX];
}

- (YSMASConstraint *)centerY {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterY];
}

- (YSMASConstraint *)baseline {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBaseline];
}

- (YSMASConstraint *(^)(YSMASAttribute))attributes {
    return ^(YSMASAttribute attrs){
        return [self addConstraintWithAttributes:attrs];
    };
}

#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100)

- (YSMASConstraint *)firstBaseline {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeFirstBaseline];
}

- (YSMASConstraint *)lastBaseline {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLastBaseline];
}

#endif


#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000)

- (YSMASConstraint *)leftMargin {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeftMargin];
}

- (YSMASConstraint *)rightMargin {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeRightMargin];
}

- (YSMASConstraint *)topMargin {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTopMargin];
}

- (YSMASConstraint *)bottomMargin {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBottomMargin];
}

- (YSMASConstraint *)leadingMargin {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeadingMargin];
}

- (YSMASConstraint *)trailingMargin {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTrailingMargin];
}

- (YSMASConstraint *)centerXWithinMargins {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterXWithinMargins];
}

- (YSMASConstraint *)centerYWithinMargins {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterYWithinMargins];
}

#endif


#pragma mark - composite Attributes

- (YSMASConstraint *)edges {
    return [self addConstraintWithAttributes:YSMASAttributeTop | YSMASAttributeLeft | YSMASAttributeRight | YSMASAttributeBottom];
}

- (YSMASConstraint *)size {
    return [self addConstraintWithAttributes:YSMASAttributeWidth | YSMASAttributeHeight];
}

- (YSMASConstraint *)center {
    return [self addConstraintWithAttributes:YSMASAttributeCenterX | YSMASAttributeCenterY];
}

#pragma mark - grouping

- (YSMASConstraint *(^)(dispatch_block_t group))group {
    return ^id(dispatch_block_t group) {
        NSInteger previousCount = self.constraints.count;
        group();

        NSArray *children = [self.constraints subarrayWithRange:NSMakeRange(previousCount, self.constraints.count - previousCount)];
        YSMASCompositeConstraint *constraint = [[YSMASCompositeConstraint alloc] initWithChildren:children];
        constraint.delegate = self;
        return constraint;
    };
}

@end
