//
//  WMImageUploadOperation.m
//  Gengmei
//
//  Created by Sean Lee on 4/7/15.
//  Copyright (c) 2015 Wanmeichuangyi. All rights reserved.
//

#import "WMImageUploadOperation.h"
#import "WMNetService.h"

@implementation WMOperationQueue

+ (NSOperationQueue *)shareQueue
{
    static NSOperationQueue *sharedQueue = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedQueue = [[WMOperationQueue alloc] init];
        [sharedQueue setMaxConcurrentOperationCount:1];
    });
    
    return sharedQueue;
}

@end


@interface WMImageUploadOperation ()
@property (nonatomic, strong) UIImage *image;
@property (nonatomic, strong) NSString *url;
@property (nonatomic, assign) float compressionQuality;
@end

@implementation WMImageUploadOperation

- (instancetype)initWithImage:(UIImage *)image url:(NSString *)url
{
    if (self = [super init])
    {
        _image = image;
        _url = url;
        _compressionQuality = 0.75;
        _params = @{@"type":@"image"};

    }
    return self;
}

- (instancetype)initWithImage:(UIImage *)image url:(NSString *)url withCompressionQuality:(float)compressionQuality
{
    if (self = [super init])
    {
        _image = image;
        _url = url;
        _compressionQuality = compressionQuality;
        _params = @{@"type":@"image"};

    }
    return self;
}

- (void)main{
    
    NSData *imageData = UIImageJPEGRepresentation(_image, _compressionQuality);
    __weak __typeof(self)weakSelf = self;
    
    [[WMNetService sharedInstance] sendUploadTaskRequestWithData:imageData fileName:@"file" name:@"file" url:_url mineType:@"image/jpeg" parameters:_params success:^(NSDictionary* jsonData) {
        NSInteger error = [jsonData[@"error"] integerValue];
        if (error == 0) {
            if (self.imageUploadFinishBlock) {
                weakSelf.imageUploadFinishBlock(jsonData);
            }
        } else {
            if (self.imageUploadFinishBlock) {
                weakSelf.imageUploadFinishBlock(nil);
            }
        }
    } failed:^(NSString *errorMsg) {
        if (self.imageUploadFinishBlock) {
            weakSelf.imageUploadFinishBlock(nil);
        }
    }];
}

- (void)startUpload{
    
    [[WMOperationQueue shareQueue] addOperation:self];
}

@end
