//
//  ICRTaskResultContentView.m
//  XFFruit
//
//  Created by Xummer on 15/4/14.
//  Copyright (c) 2015年 Xummer. All rights reserved.
//

#import "ICRTaskResultContentView.h"
#import "ICRTaskDetailContentView.h"
#import "LBorderView.h"

#define TR_VERTICAL_MARGIN          (10.0f)
#define TR_HORIZON_MARGIN           (15.0f)
#define TR_INNER_GAP                (5.0f)

@interface ICRTaskResultContentView ()

@property (strong, nonatomic) IBTUIView *m_topResultView;
@property (strong, nonatomic) IBTUILabel *m_resultLabel;
@property (strong, nonatomic) IBTUILabel *m_resultValueLabel;
@property (strong, nonatomic) IBTUIView *m_resultValueBG;
@property (strong, nonatomic) IBTUILabel *m_attachmentImageLabel;
@property (strong, nonatomic) UIImageView *m_attachImageView;
@property (strong, nonatomic) LBorderView *m_referenceView;
@property (strong, nonatomic) ICRTaskDetailContentView *m_rDetailView;

@end

@implementation ICRTaskResultContentView

#pragma mark - Life Cycle
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (!self) {
        return nil;
    }
    
    [self initSubviews];
    
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    CGSize vSize = CGSizeZero;
    CGFloat fMaxW = self.width - 2 * TR_HORIZON_MARGIN;
    CGFloat fDy = 0;
    
    [_m_resultLabel sizeToFit];
    _m_resultLabel.origin = (CGPoint){
        .x = TR_HORIZON_MARGIN,
        .y = TR_VERTICAL_MARGIN
    };
    
    CGFloat fInsert = 2;
    CGFloat fW = fMaxW - 2 * fInsert;
    vSize = CGSizeMake(fMaxW - 2 * fInsert, CGFLOAT_MAX);
    vSize = [_m_resultValueLabel widthLimitedSizeThatFits:vSize];
    _m_resultValueLabel.frame = (CGRect){
        .origin.x = fInsert,
        .origin.y = fInsert,
        .size.width = fW,
        .size.height = MAX(18, vSize.height)
    };
    
    _m_resultValueBG.frame = (CGRect){
        .origin.x = _m_resultLabel.left,
        .origin.y = _m_resultLabel.bottom + 2,
        .size.width = fMaxW,
        .size.height = _m_resultValueLabel.bottom + fInsert
    };
    
    fDy = _m_resultValueBG.bottom + TR_INNER_GAP;
    
    if (!_m_attachImageView.hidden) {
        [_m_attachmentImageLabel sizeToFit];
        _m_attachmentImageLabel.origin = (CGPoint){
            .x = _m_resultLabel.left,
            .y = fDy
        };
        
        UIImage *image = _m_attachImageView.image;
        CGFloat hWRatio =  image ? (image.size.height / image.size.width) : 1;
        
        _m_attachImageView.frame = (CGRect){
            .origin.x = _m_attachmentImageLabel.left,
            .origin.y = _m_attachmentImageLabel.bottom + 2,
            .size.width = fMaxW,
            .size.height = fMaxW * hWRatio
        };
        
        fDy = _m_attachImageView.bottom + TR_INNER_GAP;
    }
    
    _m_topResultView.frame = (CGRect){
        .origin.x = 0,
        .origin.y = 0,
        .size.width = self.width,
        .size.height = fDy
    };
    
    fDy = _m_topResultView.bottom + TR_INNER_GAP;
    
    _m_rDetailView.width = fMaxW;
    [_m_rDetailView layoutSubviews];
    
    _m_referenceView.frame = (CGRect){
        .origin.x = TR_HORIZON_MARGIN,
        .origin.y = fDy,
        .size.width = _m_rDetailView.width,
        .size.height = _m_rDetailView.height
    };
    
    fDy = _m_referenceView.bottom + TR_INNER_GAP;
    
    self.height = fDy;
}

#pragma mark - Private Method

- (void)initSubviews {
    
    // Top Result
    self.m_topResultView = [[IBTUIView alloc] init];
    _m_topResultView.backgroundColor = [UIColor colorWithR:238 g:246 b:255 a:1];
    
    [self addSubview:_m_topResultView];
    
    self.m_resultLabel =
    [[self class] titleLabelWithText:[IBTCommon localizableString:@"Process Result"]];
    [_m_topResultView addSubview:_m_resultLabel];
    
    self.m_resultValueBG = [[IBTUIView alloc] init];
    _m_resultValueBG.layer.cornerRadius = IBT_DEFAULT_CORNER_RADIUS;
    _m_resultValueBG.layer.borderWidth = 1;
    _m_resultValueBG.layer.borderColor = ICR_TINTCOLOR.CGColor;
    [_m_topResultView addSubview:_m_resultValueBG];
    
    self.m_resultValueLabel =
    [[self class] titleLabelWithText:nil];
    _m_resultValueLabel.numberOfLines = 0;
    [_m_resultValueBG addSubview:_m_resultValueLabel];

    self.m_attachmentImageLabel =
    [[self class] titleLabelWithText:[IBTCommon localizableString:@"Attachment Image"]];
    [_m_topResultView addSubview:_m_attachmentImageLabel];
    
    self.m_attachImageView = [[UIImageView alloc] init];
    [_m_topResultView addSubview:_m_attachImageView];
    
    
    // Bottom Refference View
    self.m_referenceView = [[LBorderView alloc] init];
    _m_referenceView.cornerRadius = IBT_DEFAULT_CORNER_RADIUS;
    _m_referenceView.borderType = BorderTypeDashed;
    _m_referenceView.borderWidth = .5f;
    _m_referenceView.borderColor = [UIColor lightGrayColor];
    _m_referenceView.dashPattern = 4;
    _m_referenceView.spacePattern = 2;
    [self addSubview:_m_referenceView];
    
    self.m_rDetailView = [[ICRTaskDetailContentView alloc] initWithIsAttach:YES];
    [_m_referenceView addSubview:_m_rDetailView];
}

+ (IBTUILabel *)titleLabelWithText:(NSString *)text {
    IBTUILabel *label = [[IBTUILabel alloc] init];
    label.textAlignment = NSTextAlignmentLeft;
    label.textColor = ICR_TINTCOLOR;
    label.font = [UIFont systemFontOfSize:15];
    label.text = text;
    
    return label;
}

@end

#import "ICRTask.h"
#import "ICRAttachment.h"

@implementation ICRTaskResultContentView (Configure)

- (void)updateWithTask:(ICRTask *)task {
    self.m_resultValueLabel.text = task.processResult;
    
    [_m_rDetailView updateWithTask:task];
    
    ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
        NSString * sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@ = ? ORDER BY %@", [ICRAttachment TableName], @"objectId", @"seq"];
        return [db executeQuery:sql, task.uuid ];
    };
    
    __weak typeof(self)weakSelf = self;
    ICRDatabaseFetchResultsBlock fetchResultsBlk = ^(NSArray *fetchedObjects) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        ICRAttachment *attach = [fetchedObjects count] > 2 ? fetchedObjects[ 1 ] : nil;
        if ([attach.fileName extensionIsImageType]) {
            strongSelf.m_attachImageView.hidden = NO;
            NSString *imgeUrl = [ICRHTTPController AttachmentUrlWithID:@( attach.aID )];
            [strongSelf.m_attachImageView sd_setImageWithURL:[NSURL URLWithString:imgeUrl]
                                            placeholderImage:[UIImage imageWithColor:ICR_IMAGE_BG_COLOR]
                                                   completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                                                       [strongSelf layoutSubviews];
                                                   }];
        }
        else {
            strongSelf.m_attachImageView.hidden = YES;
        }
        
        strongSelf.m_attachmentImageLabel.hidden = strongSelf.m_attachImageView.hidden;
        
        [strongSelf layoutSubviews];
    };
    
    ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
    [dbCtrl runFetchForClass:[ICRAttachment class]
                  fetchBlock:fetchBlk
           fetchResultsBlock:fetchResultsBlk];
    
}

@end
