// Copyright (c) 2013 Mutual Mobile (http://mutualmobile.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#import "MMViewController.h"
#import "CustomMMSpreadsheetView.h"
#import "MMGridCell.h"
#import "MMTopRowCell.h"
#import "MMLeftColumnCell.h"
#import "NSIndexPath+MMSpreadsheetView.h"

@interface MMViewController () <MMSpreadsheetViewDataSource, MMSpreadsheetViewDelegate>

@property (nonatomic, strong) NSMutableSet *selectedGridCells;
@property (nonatomic, strong) NSString *cellDataBuffer;
@property (nonatomic, strong) CustomMMSpreadsheetView *spreadSheetView;


@end

@implementation MMViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSUInteger rows = 4;
    NSUInteger cols = 4;
    
    // Create some fake grid data for the demo.
    self.tableData = [NSMutableArray array];
    
    for (NSUInteger rowNumber = 0; rowNumber < rows; rowNumber++) {
        NSMutableArray *row = [NSMutableArray array];
        for (NSUInteger columnNumber = 0; columnNumber < cols; columnNumber++) {
            [row addObject:@""];
        }
        [self.tableData addObject:row];
    }
    
    self.selectedGridCells = [NSMutableSet set];
    
    // Create the spreadsheet in code.
    CustomMMSpreadsheetView *spreadSheetView = [[CustomMMSpreadsheetView alloc] initWithNumberOfHeaderRows:1 numberOfHeaderColumns:1 frame:self.view.bounds];
    self.spreadSheetView = spreadSheetView;
    spreadSheetView.tableData = self.tableData;
    spreadSheetView.bounces = NO;
    spreadSheetView.backgroundColor = [UIColor whiteColor];
    // Register your cell classes.
    [spreadSheetView registerCellClass:[MMGridCell class] forCellWithReuseIdentifier:@"GridCell"];
    [spreadSheetView registerCellClass:[MMTopRowCell class] forCellWithReuseIdentifier:@"TopRowCell"];
    [spreadSheetView registerCellClass:[MMTopRowCell class] forCellWithReuseIdentifier:@"BottomRowCell"];
    [spreadSheetView registerCellClass:[MMLeftColumnCell class] forCellWithReuseIdentifier:@"LeftColumnCell"];

    // Set the delegate & datasource for the spreadsheet view.
    spreadSheetView.delegate = self;
    spreadSheetView.dataSource = self;
    
    // Add the spreadsheet view as a subview.
    [self.view addSubview:spreadSheetView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - MMSpreadsheetViewDataSource

- (CGSize)spreadsheetView:(CustomMMSpreadsheetView *)spreadsheetView sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat leftColumnWidth = 120.0f;
    CGFloat topRowHeight = 60.0f;
    CGFloat gridCellWidth = 100;
    CGFloat gridCellHeight = 50.0f;

    // Upper left.
    if (indexPath.mmSpreadsheetRow == 0 && indexPath.mmSpreadsheetColumn == 0) {
        return CGSizeMake(leftColumnWidth, topRowHeight);
    }
    
    // Upper right.
    if (indexPath.mmSpreadsheetRow == 0 && indexPath.mmSpreadsheetColumn > 0) {
        return CGSizeMake(gridCellWidth, topRowHeight);
    }
    
    // Lower left.
    if (indexPath.mmSpreadsheetRow > 0 && indexPath.mmSpreadsheetColumn == 0) {
        return CGSizeMake(leftColumnWidth, gridCellHeight);
    }
    
    return CGSizeMake(gridCellWidth, gridCellHeight);
}

- (NSInteger)numberOfRowsInSpreadsheetView:(CustomMMSpreadsheetView *)spreadsheetView {
    NSInteger rows = [self.tableData count];
    return rows;
}

- (NSInteger)numberOfColumnsInSpreadsheetView:(CustomMMSpreadsheetView *)spreadsheetView {
    NSArray *rowData = [self.tableData lastObject];
    NSInteger cols = [rowData count];
    return cols;
}

- (UICollectionViewCell *)spreadsheetView:(CustomMMSpreadsheetView *)spreadsheetView cellForItemAtIndexPath:(NSIndexPath *)indexPath collectionView:(UICollectionView *)collectionView{
    UICollectionViewCell *cell = nil;
    if (indexPath.mmSpreadsheetRow == 0 && indexPath.mmSpreadsheetColumn == 0) {
        // Upper left.
        cell = [spreadsheetView dequeueReusableCellWithReuseIdentifier:@"GridCell" forIndexPath:indexPath];
//        NSLog(@"顶部左边 %p",cell);
//        NSLog(@"clumn %lu row %lu", indexPath.mmSpreadsheetColumn, indexPath.mmSpreadsheetRow);
        MMGridCell *gc = (MMGridCell *)cell;
        NSArray *colData = [self.tableData objectAtIndex:indexPath.mmSpreadsheetRow];
        NSString *rowData = [colData objectAtIndex:indexPath.mmSpreadsheetColumn];
        gc.textLabel.text = rowData;
        gc.textLabel.numberOfLines = 0;
        cell.backgroundColor = [UIColor colorWithRed:0.996 green:0.976 blue:0.953 alpha:1.000];
    }
    else if (indexPath.mmSpreadsheetRow == 0 && indexPath.mmSpreadsheetColumn > 0 && collectionView.tag != MMSpreadsheetViewCollectionBottom) {
        // Upper right. 顶部那一行
        cell = [spreadsheetView dequeueReusableCellWithReuseIdentifier:@"TopRowCell" forIndexPath:indexPath];
//        NSLog(@"顶部右边 %p",cell);
//        NSLog(@"clumn %lu row %lu", indexPath.mmSpreadsheetColumn, indexPath.mmSpreadsheetRow);
        MMTopRowCell *tr = (MMTopRowCell *)cell;
        NSArray *colData = [self.tableData objectAtIndex:indexPath.mmSpreadsheetRow];
        NSString *rowData = [colData objectAtIndex:indexPath.mmSpreadsheetColumn];
        tr.textLabel.text = rowData;
        if (indexPath.mmSpreadsheetColumn == 1) {
            tr.textLabel.textColor = [UIColor redColor];
        }else{
            tr.textLabel.textColor = [UIColor blackColor];
        }
        tr.textLabel.numberOfLines = 2;
        cell.backgroundColor = [UIColor colorWithRed:0.996 green:0.976 blue:0.953 alpha:1.000];
    }
    else if (indexPath.mmSpreadsheetRow > 0 && indexPath.mmSpreadsheetColumn == 0) {
        // Lower left.
        cell = [spreadsheetView dequeueReusableCellWithReuseIdentifier:@"LeftColumnCell" forIndexPath:indexPath];
        NSLog(@"左栏 %p", cell);
        NSLog(@"clumn %lu row %lu", indexPath.mmSpreadsheetColumn, indexPath.mmSpreadsheetRow);
        MMLeftColumnCell *lc = (MMLeftColumnCell *)cell;
        NSArray *colData = [self.tableData objectAtIndex:indexPath.mmSpreadsheetRow];
        NSString *rowData = [colData objectAtIndex:indexPath.mmSpreadsheetColumn];
        lc.textLabel.text = rowData;
        BOOL isDarker = indexPath.mmSpreadsheetRow % 2 == 0;
        if (isDarker) {
            cell.backgroundColor = [UIColor colorWithRed:222.0f / 255.0f green:243.0f / 255.0f blue:250.0f / 255.0f alpha:1.0f];
        } else {
            cell.backgroundColor = [UIColor colorWithRed:233.0f / 255.0f green:247.0f / 255.0f blue:252.0f / 255.0f alpha:1.0f];
        }
    }
    else  if (indexPath.mmSpreadsheetRow > 0 && indexPath.mmSpreadsheetColumn > 0 && indexPath.mmSpreadsheetRow < self.tableData.count - 1 ) {
        // Lower right.
        cell = [spreadsheetView dequeueReusableCellWithReuseIdentifier:@"GridCell" forIndexPath:indexPath];
        NSLog(@"LR %p",cell);
        NSLog(@"clumn %lu row %lu", indexPath.mmSpreadsheetColumn, indexPath.mmSpreadsheetRow);
        MMGridCell *gc = (MMGridCell *)cell;
        NSArray *colData = [self.tableData objectAtIndex:indexPath.mmSpreadsheetRow];
        NSString *rowData = [colData objectAtIndex:indexPath.mmSpreadsheetColumn];
        gc.textLabel.text = rowData;
        if (indexPath.mmSpreadsheetColumn == 1) {
            gc.textLabel.textColor = [UIColor redColor];
        }else{
            gc.textLabel.textColor = [UIColor blackColor];
        }
        BOOL isDarker = indexPath.mmSpreadsheetRow % 2 == 0;
        if (isDarker) {
            cell.backgroundColor = [UIColor colorWithRed:242.0f / 255.0f green:242.0f / 255.0f blue:242.0f / 255.0f alpha:1.0f];
        } else {
            cell.backgroundColor = [UIColor colorWithRed:250.0f / 255.0f green:250.0f / 255.0f blue:250.0f / 255.0f alpha:1.0f];
        }
    }else{
        cell = [spreadsheetView dequeueReusableCellWithReuseIdentifier:@"BottomRowCell" forIndexPath:indexPath];
        NSLog(@"BR %p",cell);
        NSLog(@"clumn %lu row %lu", indexPath.mmSpreadsheetColumn, indexPath.mmSpreadsheetRow);
        MMTopRowCell *tr = (MMTopRowCell *)cell;
        NSArray *colData = [self.tableData lastObject];
        NSString *rowData = [colData objectAtIndex:indexPath.mmSpreadsheetColumn];
        tr.textLabel.text = rowData;
        if (indexPath.mmSpreadsheetColumn == 1) {
            tr.textLabel.textColor = [UIColor redColor];
        }else{
            tr.textLabel.textColor = [UIColor blackColor];
        }
        cell.backgroundColor = [UIColor whiteColor];
    }

    return cell;
}

#pragma mark - MMSpreadsheetViewDelegate

- (void)spreadsheetView:(CustomMMSpreadsheetView *)spreadsheetView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.selectedGridCells containsObject:indexPath]) {
        [self.selectedGridCells removeObject:indexPath];
        [spreadsheetView deselectItemAtIndexPath:indexPath animated:YES];
    } else {
        [self.selectedGridCells removeAllObjects];
        [self.selectedGridCells addObject:indexPath];
    }
}

- (BOOL)spreadsheetView:(CustomMMSpreadsheetView *)spreadsheetView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (BOOL)spreadsheetView:(CustomMMSpreadsheetView *)spreadsheetView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
    
    /*
     These are the selectors the sender (a UIMenuController) sends by default.
     
     _insertImage:
     cut:
     copy:
     select:
     selectAll:
     paste:
     delete:
     _promptForReplace:
     _showTextStyleOptions:
     _define:
     _addShortcut:
     _accessibilitySpeak:
     _accessibilitySpeakLanguageSelection:
     _accessibilityPauseSpeaking:
     makeTextWritingDirectionRightToLeft:
     makeTextWritingDirectionLeftToRight:
     
     We're only interested in 3 of them at this point
     */
    if (action == @selector(cut:) ||
        action == @selector(copy:) ||
        action == @selector(paste:)) {
        return YES;
    }
    return NO;
}

- (void)spreadsheetView:(CustomMMSpreadsheetView *)spreadsheetView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
    NSMutableArray *rowData = [self.tableData objectAtIndex:indexPath.mmSpreadsheetRow];
    if (action == @selector(cut:)) {
        self.cellDataBuffer = [rowData objectAtIndex:indexPath.row];
        [rowData replaceObjectAtIndex:indexPath.row withObject:@""];
        [spreadsheetView reloadData];
    } else if (action == @selector(copy:)) {
        self.cellDataBuffer = [rowData objectAtIndex:indexPath.row];
    } else if (action == @selector(paste:)) {
        if (self.cellDataBuffer) {
            [rowData replaceObjectAtIndex:indexPath.row withObject:self.cellDataBuffer];
            [spreadsheetView reloadData];
        }
    }
}

- (void)reloadData {
    [self.spreadSheetView reloadData];
}
@end
