//
//  PhotoWall.m
//  PhotoDemo
//
//  Created by Harry on 12-12-6.
//  Copyright (c) 2012年 Harry. All rights reserved.
//

#import "HGPhotoWall.h"

#import "HGPhoto.h"

@interface HGPhotoWall() <HGPhotoDelegate>

@property (strong, nonatomic) UILabel *labelDescription;

@property (strong, nonatomic) NSMutableArray *arrayPositions;
@property (strong, nonatomic) NSMutableArray *arrayPhotos;
@property (nonatomic) BOOL isEditModel;

@end

#define kImagCount 3
#define kPadding (20.0 / 320.0 * self.width)/(kImagCount + 1)
#define kImagWH ((self.width - (kImagCount + 1.0) * kPadding) / kImagCount)
#define kFrameHeight 95.
#define kFrameHeight2x 175.

#define kImagePositionx @"positionx"
#define kImagePositiony @"positiony"

@implementation HGPhotoWall


- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];//CGRectMake(0., 0., 320., 0.)];
    if (self) {
        self.backgroundColor = [UIColor darkGrayColor];
        self.arrayPositions = [NSMutableArray arrayWithCapacity:1];
        self.arrayPhotos = [NSMutableArray arrayWithCapacity:1];
        
        self.labelDescription = [[UILabel alloc] initWithFrame:CGRectMake(10., 0., 300., 18.)];
        self.labelDescription.backgroundColor = [UIColor clearColor];
        self.labelDescription.textColor = [UIColor whiteColor];
        self.labelDescription.font = [UIFont systemFontOfSize:12.];
        self.labelDescription.textAlignment = NSTextAlignmentLeft;
        
        [self addSubview:self.labelDescription];
        
        self.labelDescription.hidden = YES;
        self.labelDescription.text = @"拖拽图片可以排列顺序, 点击添加照片.";
    }
    return self;
}
- (void)layoutSubviews {
    [super layoutSubviews];
}
- (void)setPhotos:(NSArray*)photos
{
    NSInteger col = photos.count % kImagCount; //列
    NSInteger row = photos.count / kImagCount;//行
    CGFloat x,y;
    for (int irow = 0; irow < row + 1; irow ++) {
        y = 15.0 / 568 * self.height + kImagWH * irow + irow * kPadding;
        if (irow < row ) {
            for (int jcol = 0; jcol < kImagCount; jcol ++) {
                x = kPadding * (jcol + 1) + kImagWH * jcol;
                [self.arrayPositions addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%f",x],kImagePositionx,[NSString stringWithFormat:@"%f",y],kImagePositiony, nil] ];
            }

        }
        else {
            for (int jcol = 0; jcol < col+1; jcol ++) {//col+1 表示多加的add按钮的位置
                x = kPadding * (jcol + 1) + kImagWH * jcol;
                [self.arrayPositions addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%f",x],kImagePositionx,[NSString stringWithFormat:@"%f",y],kImagePositiony, nil] ];
            }
            
        }
        
    }
    [self.arrayPhotos removeAllObjects];
    NSUInteger count = [photos count];
    for (int i=0; i<count; i++) {
        NSDictionary *dictionaryTemp = [self.arrayPositions objectAtIndex:i];
        CGFloat originx = [[dictionaryTemp objectForKey:kImagePositionx] floatValue];
        CGFloat originy = [[dictionaryTemp objectForKey:kImagePositiony] floatValue];
        HGPhoto *photoTemp = [[HGPhoto alloc]initWithOrigin:CGPointMake(originx, originy) andLength:kImagWH];//[[HGPhoto alloc] initWithOrigin:CGPointMake(originx, originy)];
        photoTemp.delegate = self;
        [photoTemp setPhotoUrl:[photos objectAtIndex:i]];
        [self addSubview:photoTemp];
        [self.arrayPhotos addObject:photoTemp];
    }
    
    NSDictionary *dictionaryTemp = [self.arrayPositions objectAtIndex:count];
    CGFloat originx = [[dictionaryTemp objectForKey:kImagePositionx] floatValue];
    CGFloat originy = [[dictionaryTemp objectForKey:kImagePositiony] floatValue];
    HGPhoto *photoTemp = [[HGPhoto alloc]initWithOrigin:CGPointMake(originx, originy) andLength:kImagWH];//[[HGPhoto alloc] initWithOrigin:CGPointMake(originx, originy)];
    photoTemp.delegate = self;
    photoTemp.hidden = YES;
    [photoTemp setPhotoType:PhotoTypeAdd];
    [self.arrayPhotos addObject:photoTemp];
    [self addSubview:photoTemp];
    
    CGFloat frameHeight = -1;
    if (count > kImagCount) {
        frameHeight = kFrameHeight2x;
    } else {
        frameHeight = kFrameHeight;
    }

    //self.frame = CGRectMake(0., 0., 320., frameHeight);
}

- (void)setEditModel:(BOOL)canEdit
{
    self.isEditModel = canEdit;
    if (self.isEditModel) {
        HGPhoto *viewTemp = [self.arrayPhotos lastObject];
        viewTemp.hidden = NO;
        self.labelDescription.hidden = NO;
    } else {
        HGPhoto *viewTemp = [self.arrayPhotos lastObject];
        viewTemp.hidden = YES;
        self.labelDescription.hidden = YES;
    }
    
    NSUInteger count = [self.arrayPhotos count]-1;
    for (int i=0; i<count; i++) {
        HGPhoto *viewTemp = [self.arrayPhotos objectAtIndex:i];
        [viewTemp setEditModel:self.isEditModel];
    }
    [self reloadPhotos:NO];
}

- (void)addPhoto:(NSString*)string
{
    NSInteger col = _arrayPositions.count % kImagCount;
    NSInteger row = _arrayPositions.count / kImagCount;
    CGFloat x,y;
    x = kPadding * (col + 1) + kImagCount * col;
    y = 15.0 / 568 * self.height + kImagWH * row +  row * kPadding ;
    [self.arrayPositions addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%f",x],kImagePositionx,[NSString stringWithFormat:@"%f",y],kImagePositiony, nil] ];
//    if (_arrayPositions.count % 4 ) {
//        <#statements#>
//    }
    NSUInteger index = [self.arrayPhotos count] - 1;
    NSDictionary *dictionaryTemp = [self.arrayPositions objectAtIndex:index ];
    CGFloat originx = [[dictionaryTemp objectForKey:kImagePositionx] floatValue];
    CGFloat originy = [[dictionaryTemp objectForKey:kImagePositiony] floatValue];
    
    HGPhoto *photoTemp = [[HGPhoto alloc]initWithOrigin:CGPointMake(originx, originy) andLength:kImagWH];//[[HGPhoto alloc] initWithOrigin:CGPointMake(originx, originy)];
    photoTemp.delegate = self;
    [photoTemp setPhotoUrl:string];
    
    [self.arrayPhotos insertObject:photoTemp atIndex:index];
    [self addSubview:photoTemp];
    [self reloadPhotos:YES];
   
}

#pragma  通过获取相册里面的图片资源来
- (void)addPhotoImg: (UIImage *)img {
    NSInteger col = _arrayPositions.count % kImagCount;
    NSInteger row = _arrayPositions.count / kImagCount;
    CGFloat x,y;
//    NSLog(@"%lf, %lf",kPadding,kImagWH);
    x = kPadding * (col + 1) + kImagWH * col;
    y = 15.0 / 568 * self.height + kImagWH * row  + kPadding * row;
    [self.arrayPositions addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%f",x],kImagePositionx,[NSString stringWithFormat:@"%f",y],kImagePositiony, nil] ];
  
    NSUInteger index = [self.arrayPhotos count] - 1;
    NSDictionary *dictionaryTemp = [self.arrayPositions objectAtIndex:index ];
    CGFloat originx = [[dictionaryTemp objectForKey:kImagePositionx] floatValue];
    CGFloat originy = [[dictionaryTemp objectForKey:kImagePositiony] floatValue];
    
    HGPhoto *photoTemp = [[HGPhoto alloc]initWithOrigin:CGPointMake(originx, originy) andLength:kImagWH];//[[HGPhoto alloc] initWithOrigin:CGPointMake(originx, originy)];
    photoTemp.delegate = self;
    [photoTemp setPhotoImg:img];
    
    [self.arrayPhotos insertObject:photoTemp atIndex:index];
    [self addSubview:photoTemp];
    [self reloadPhotos:YES];
    
  
}


- (void)deletePhotoByIndex:(NSUInteger)index
{
    [_arrayPositions removeLastObject];
    HGPhoto *photoTemp = [self.arrayPhotos objectAtIndex:index];
    [self.arrayPhotos removeObject:photoTemp];
    [photoTemp removeFromSuperview];
    [self reloadPhotos:YES];
}

#pragma mark - Photo

- (void)photoTaped:(HGPhoto *)photo
{
    NSUInteger type = [photo getPhotoType];
    if (type == PhotoTypeAdd) {
//        if ([self.delegate respondsToSelector:@selector(photoWallAddAction)]) {
//            [self.delegate photoWallAddAction];
//        }
        if ([self.delegate respondsToSelector:@selector(photowallChoosePhontoes)]) {
            [self.delegate photowallChoosePhontoes];
        }
    } else if (type == PhotoTypePhoto) {
        NSUInteger index = [self.arrayPhotos indexOfObject:photo];
        if ([self.delegate respondsToSelector:@selector(photoWallPhotoTaped:)]) {
            [self.delegate photoWallPhotoTaped:photo];
            //[self.delegate photoWallPhotoDel:index];
        }
    }
}
- (void)photoDel:(HGPhoto *)photo {
    NSUInteger type = [photo getPhotoType];
        if (type == PhotoTypePhoto) {
            NSUInteger index = [self.arrayPhotos indexOfObject:photo];
            [self.delegate photoWallPhotoDel:index];
        }

}
//- (void)photoDel:(HGPhoto *)photo {
//     NSUInteger type = [photo getPhotoType];
//    if (type == PhotoTypePhoto) {
//        NSUInteger index = [self.arrayPhotos indexOfObject:photo];
//        [self.delegate ph]
//    }
//}
- (void)photoMoveFinished:(HGPhoto*)photo
{
    CGPoint pointPhoto = CGPointMake(photo.frame.origin.x, photo.frame.origin.y);
    CGFloat space = -1;
    NSUInteger oldIndex = [self.arrayPhotos indexOfObject:photo];
    NSUInteger newIndex = -1;
    
    NSUInteger count = [self.arrayPhotos count] - 1;
    for (int i=0; i<count; i++) {
        NSDictionary *dictionaryTemp = [self.arrayPositions objectAtIndex:i];
        CGFloat originx = [[dictionaryTemp objectForKey:kImagePositionx] floatValue];
        CGFloat originy = [[dictionaryTemp objectForKey:kImagePositiony] floatValue];
        CGPoint pointTemp = CGPointMake(originx, originy);
        CGFloat spaceTemp = [self spaceToPoint:pointPhoto FromPoint:pointTemp];
        if (space < 0) {
            space = spaceTemp;
            newIndex = i;
        } else {
            if (spaceTemp < space) {
                space = spaceTemp;
                newIndex = i;
            }
        }
    }
    
    [self.arrayPhotos removeObject:photo];
    [self.arrayPhotos insertObject:photo atIndex:newIndex];
    
    [self reloadPhotos:NO];
    
    if ([self.delegate respondsToSelector:@selector(photoWallMovePhotoFromIndex:toIndex:)]) {
        [self.delegate photoWallMovePhotoFromIndex:oldIndex toIndex:newIndex];
    }
}

- (void)reloadPhotos:(BOOL)add
{
    NSUInteger count = -1;
    if (add) {
        count = [self.arrayPhotos count];
    } else {
        count = [self.arrayPhotos count] - 1;
    }
    for (int i=0; i<count; i++) {
        NSDictionary *dictionaryTemp = [self.arrayPositions objectAtIndex:i];
        CGFloat originx = [[dictionaryTemp objectForKey:kImagePositionx] floatValue];
        CGFloat originy = [[dictionaryTemp objectForKey:kImagePositiony] floatValue];
        
        HGPhoto *photoTemp = [self.arrayPhotos objectAtIndex:i];
        [photoTemp moveToPosition:CGPointMake(originx, originy)];
    }
    
    CGFloat frameHeight = -1;
    NSUInteger countPhoto = [self.arrayPhotos count];
    if (self.isEditModel) {
        if (countPhoto > kImagCount) {
            frameHeight = kFrameHeight2x + 20.;
        } else {
            frameHeight = kFrameHeight + 20.;
        }
        self.labelDescription.frame = CGRectMake(self.labelDescription.frame.origin.x, frameHeight - 20., self.labelDescription.frame.size.width, self.labelDescription.frame.size.height);
    } else {
        if (countPhoto > 5) {
            frameHeight = kFrameHeight2x;
        } else {
            frameHeight = kFrameHeight;
        }
    }
   // self.frame = CGRectMake(0., 0., 320., frameHeight);
}

- (CGFloat)spaceToPoint:(CGPoint)point FromPoint:(CGPoint)otherPoint
{
    float x = point.x - otherPoint.x;
    float y = point.y - otherPoint.y;
    return sqrt(x * x + y * y);
}

@end
