/*
 * This file is part of the YSSDWebImage package.
 * (c) Olivier Poitrey <rs@dailymotion.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

#import "UIButton+YSWebCache.h"

#if YSSD_UIKIT

#import "objc/runtime.h"
#import "UIView+YSWebCacheOperation.h"
#import "UIView+YSWebCache.h"
#import "YSSDInternalMacros.h"

static char imageURLStorageKey;

typedef NSMutableDictionary<NSString *, NSURL *> YSSDStateImageURLDictionary;

static inline NSString * imageURLKeyForState(UIControlState state) {
    return [NSString stringWithFormat:@"image_%lu", (unsigned long)state];
}

static inline NSString * backgroundImageURLKeyForState(UIControlState state) {
    return [NSString stringWithFormat:@"backgroundImage_%lu", (unsigned long)state];
}

static inline NSString * imageOperationKeyForState(UIControlState state) {
    return [NSString stringWithFormat:@"UIButtonImageOperation%lu", (unsigned long)state];
}

static inline NSString * backgroundImageOperationKeyForState(UIControlState state) {
    return [NSString stringWithFormat:@"UIButtonBackgroundImageOperation%lu", (unsigned long)state];
}

@implementation UIButton (YSWebCache)

#pragma mark - Image

- (nullable NSURL *)yssd_currentImageURL {
    NSURL *url = self.yssd_imageURLStorage[imageURLKeyForState(self.state)];

    if (!url) {
        url = self.yssd_imageURLStorage[imageURLKeyForState(UIControlStateNormal)];
    }

    return url;
}

- (nullable NSURL *)yssd_imageURLForState:(UIControlState)state {
    return self.yssd_imageURLStorage[imageURLKeyForState(state)];
}

- (void)yssd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state {
    [self yssd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil];
}

- (void)yssd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder {
    [self yssd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil];
}

- (void)yssd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(YSSDWebImageOptions)options {
    [self yssd_setImageWithURL:url forState:state placeholderImage:placeholder options:options progress:nil completed:nil];
}

- (void)yssd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(YSSDWebImageOptions)options context:(nullable YSSDWebImageContext *)context {
    [self yssd_setImageWithURL:url forState:state placeholderImage:placeholder options:options context:context progress:nil completed:nil];
}

- (void)yssd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state completed:(nullable YSSDExternalCompletionBlock)completedBlock {
    [self yssd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock];
}

- (void)yssd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder completed:(nullable YSSDExternalCompletionBlock)completedBlock {
    [self yssd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock];
}

- (void)yssd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(YSSDWebImageOptions)options completed:(nullable YSSDExternalCompletionBlock)completedBlock {
    [self yssd_setImageWithURL:url forState:state placeholderImage:placeholder options:options progress:nil completed:completedBlock];
}

- (void)yssd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(YSSDWebImageOptions)options progress:(nullable YSSDImageLoaderProgressBlock)progressBlock completed:(nullable YSSDExternalCompletionBlock)completedBlock {
    [self yssd_setImageWithURL:url forState:state placeholderImage:placeholder options:options context:nil progress:progressBlock completed:completedBlock];
}

- (void)yssd_setImageWithURL:(nullable NSURL *)url
                  forState:(UIControlState)state
          placeholderImage:(nullable UIImage *)placeholder
                   options:(YSSDWebImageOptions)options
                   context:(nullable YSSDWebImageContext *)context
                  progress:(nullable YSSDImageLoaderProgressBlock)progressBlock
                 completed:(nullable YSSDExternalCompletionBlock)completedBlock {
    if (!url) {
        [self.yssd_imageURLStorage removeObjectForKey:imageURLKeyForState(state)];
    } else {
        self.yssd_imageURLStorage[imageURLKeyForState(state)] = url;
    }
    
    YSSDWebImageMutableContext *mutableContext;
    if (context) {
        mutableContext = [context mutableCopy];
    } else {
        mutableContext = [NSMutableDictionary dictionary];
    }
    mutableContext[YSSDWebImageContextSetImageOperationKey] = imageOperationKeyForState(state);
    @WeakObj(self);
    [self yssd_internalSetImageWithURL:url
                    placeholderImage:placeholder
                             options:options
                             context:mutableContext
                       setImageBlock:^(UIImage * _Nullable image, NSData * _Nullable imageData, YSSDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                           @StrongObj(self);
                           [self setImage:image forState:state];
                       }
                            progress:progressBlock
                           completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, YSSDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
                               if (completedBlock) {
                                   completedBlock(image, error, cacheType, imageURL);
                               }
                           }];
}

#pragma mark - Background Image

- (nullable NSURL *)yssd_currentBackgroundImageURL {
    NSURL *url = self.yssd_imageURLStorage[backgroundImageURLKeyForState(self.state)];
    
    if (!url) {
        url = self.yssd_imageURLStorage[backgroundImageURLKeyForState(UIControlStateNormal)];
    }
    
    return url;
}

- (nullable NSURL *)yssd_backgroundImageURLForState:(UIControlState)state {
    return self.yssd_imageURLStorage[backgroundImageURLKeyForState(state)];
}

- (void)yssd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state {
    [self yssd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil];
}

- (void)yssd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder {
    [self yssd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil];
}

- (void)yssd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(YSSDWebImageOptions)options {
    [self yssd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options progress:nil completed:nil];
}

- (void)yssd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(YSSDWebImageOptions)options context:(nullable YSSDWebImageContext *)context {
    [self yssd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options context:context progress:nil completed:nil];
}

- (void)yssd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state completed:(nullable YSSDExternalCompletionBlock)completedBlock {
    [self yssd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock];
}

- (void)yssd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder completed:(nullable YSSDExternalCompletionBlock)completedBlock {
    [self yssd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock];
}

- (void)yssd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(YSSDWebImageOptions)options completed:(nullable YSSDExternalCompletionBlock)completedBlock {
    [self yssd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options progress:nil completed:completedBlock];
}

- (void)yssd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(YSSDWebImageOptions)options progress:(nullable YSSDImageLoaderProgressBlock)progressBlock completed:(nullable YSSDExternalCompletionBlock)completedBlock {
    [self yssd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options context:nil progress:progressBlock completed:completedBlock];
}

- (void)yssd_setBackgroundImageWithURL:(nullable NSURL *)url
                            forState:(UIControlState)state
                    placeholderImage:(nullable UIImage *)placeholder
                             options:(YSSDWebImageOptions)options
                             context:(nullable YSSDWebImageContext *)context
                            progress:(nullable YSSDImageLoaderProgressBlock)progressBlock
                           completed:(nullable YSSDExternalCompletionBlock)completedBlock {
    if (!url) {
        [self.yssd_imageURLStorage removeObjectForKey:backgroundImageURLKeyForState(state)];
    } else {
        self.yssd_imageURLStorage[backgroundImageURLKeyForState(state)] = url;
    }
    
    YSSDWebImageMutableContext *mutableContext;
    if (context) {
        mutableContext = [context mutableCopy];
    } else {
        mutableContext = [NSMutableDictionary dictionary];
    }
    mutableContext[YSSDWebImageContextSetImageOperationKey] = backgroundImageOperationKeyForState(state);
    @WeakObj(self);
    [self yssd_internalSetImageWithURL:url
                    placeholderImage:placeholder
                             options:options
                             context:mutableContext
                       setImageBlock:^(UIImage * _Nullable image, NSData * _Nullable imageData, YSSDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                           @StrongObj(self);
                           [self setBackgroundImage:image forState:state];
                       }
                            progress:progressBlock
                           completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, YSSDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
                               if (completedBlock) {
                                   completedBlock(image, error, cacheType, imageURL);
                               }
                           }];
}

#pragma mark - Cancel

- (void)yssd_cancelImageLoadForState:(UIControlState)state {
    [self yssd_cancelImageLoadOperationWithKey:imageOperationKeyForState(state)];
}

- (void)yssd_cancelBackgroundImageLoadForState:(UIControlState)state {
    [self yssd_cancelImageLoadOperationWithKey:backgroundImageOperationKeyForState(state)];
}

#pragma mark - Private

- (YSSDStateImageURLDictionary *)yssd_imageURLStorage {
    YSSDStateImageURLDictionary *storage = objc_getAssociatedObject(self, &imageURLStorageKey);
    if (!storage) {
        storage = [NSMutableDictionary dictionary];
        objc_setAssociatedObject(self, &imageURLStorageKey, storage, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }

    return storage;
}

@end

#endif
