/*
 Copyright (c) 2015, OpenEmu Team

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:
     * Redistributions of source code must retain the above copyright
       notice, this list of conditions and the following disclaimer.
     * Redistributions in binary form must reproduce the above copyright
       notice, this list of conditions and the following disclaimer in the
       documentation and/or other materials provided with the distribution.
     * Neither the name of the OpenEmu Team nor the
       names of its contributors may be used to endorse or promote products
       derived from this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY OpenEmu Team ''AS IS'' AND ANY
 EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED. IN NO EVENT SHALL OpenEmu Team BE LIABLE FOR ANY
 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#import "OELibraryGamesViewController.h"

#import "OEGameCollectionViewController.h"
#import "OESidebarController.h"
#import "OELibrarySplitView.h"
#import "OELibraryController.h"

#import "OEDBCollection.h"
#import "OEDBSystem+CoreDataProperties.h"

@import OpenEmuKit;

#import "OpenEmu-Swift.h"

#define MainMenu_View_GridTag      301
#define MainMenu_View_ListTag      303

NSString * const OESkipDiscGuideMessageKey = @"OESkipDiscGuideMessageKey";

@implementation OELibraryGamesViewController
@synthesize libraryController = _libraryController;

- (void)viewDidLoad
{
    [super viewDidLoad];
        
    [self _assignLibraryController];

    NSNotificationCenter *noc = [NSNotificationCenter defaultCenter];
    [noc addObserver:self selector:@selector(_updateCollectionContentsFromSidebar:) name:OESidebarSelectionDidChangeNotification object:[self sidebarController]];

    NSView *collectionView = [[self collectionController] view];
    NSView *collectionViewContainer = [self collectionViewContainer];

    [collectionView setFrame:[collectionViewContainer bounds]];
    [collectionView setAutoresizingMask:NSViewWidthSizable|NSViewHeightSizable];
    [collectionViewContainer addSubview:collectionView];

    [self addChildViewController:[self sidebarController]];
    [self addChildViewController:[self collectionController]];
    
    [self _updateCollectionContentsFromSidebar:nil];
}

- (void)viewWillAppear
{
    [super viewWillAppear];
    
    [self _setupToolbar];

    self.view.needsDisplay = YES;
}

- (void)viewDidAppear
{
    [super viewDidAppear];
    [self.collectionController updateBlankSlate];
}

- (void)_setupToolbar
{
    OELibraryController *libraryController = self.libraryController;
    OELibraryToolbar *toolbar = libraryController.toolbar;

    toolbar.gridSizeSlider.enabled = YES;
    toolbar.viewModeSelector.enabled = YES;
    
    OECollectionViewControllerViewTag selectedViewTag = self.collectionController.selectedViewTag;
    BOOL setGridView = selectedViewTag == OEGridViewTag || selectedViewTag == OEBlankSlateTag;
    toolbar.viewModeSelector.selectedSegment = setGridView ? 0 : 1;

    NSSearchField *field = toolbar.searchField;
    field.searchMenuTemplate = nil;
    field.enabled = NO;
    field.stringValue = @"";
}

- (BOOL)validateToolbarItem:(id)item
{
    OELibraryToolbar *toolbar = self.libraryController.toolbar;
    OECollectionViewControllerViewTag selectedViewTag = self.collectionController.selectedViewTag;
    
    if ([item action] == @selector(switchToView:))
    {
        if (selectedViewTag != OEBlankSlateTag)
        {
            BOOL setGridView = selectedViewTag == OEGridViewTag;
            toolbar.viewModeSelector.selectedSegment = setGridView ? 0 : 1;
            return YES;
        }
        else
        {
            return NO;
        }
    }
    else if ([item action] == @selector(changeGridSize:) ||
             [item action] == @selector(decreaseGridSize:) ||
             [item action] == @selector(increaseGridSize:))
    {
        return selectedViewTag == OEGridViewTag;
    }
    else if ([item action] == @selector(search:))
    {
        if (selectedViewTag != OEBlankSlateTag)
        {
            return YES;
        }
        else
        {
            return NO;
        }
    }
    return YES;
}

#pragma mark - OELibrarySubviewController

- (NSArray<OEDBGame *> *)selectedGames
{
    return [[self collectionController] selectedGames];
}

- (OELibraryController *)libraryController
{
    return _libraryController;
}

- (void)setLibraryController:(OELibraryController *)libraryController
{
    _libraryController = libraryController;
    [self _assignLibraryController];
}

- (void)_assignLibraryController
{
    [[self sidebarController] setDatabase:[_libraryController database]];
    [[self collectionController] setLibraryController:_libraryController];
    [[self gameScannerController] setLibraryController:_libraryController];
}

#pragma mark - Toolbar
- (IBAction)addCollectionAction:(id)sender
{
    [[self sidebarController] addCollectionAction:sender];
}

- (IBAction)switchToGridView:(id)sender
{
    [[self collectionController] switchToGridView:sender];
    
    // Update state of respective view menu items.
    NSMenu *viewMenu = [[[NSApp mainMenu] itemAtIndex:3] submenu];
    [[viewMenu itemWithTag:MainMenu_View_GridTag] setState:NSControlStateValueOn];
    [[viewMenu itemWithTag:MainMenu_View_ListTag] setState:NSControlStateValueOff];
}

- (IBAction)switchToListView:(id)sender
{
    [[self collectionController] switchToListView:sender];
    
    // Update state of respective view menu items.
    NSMenu *viewMenu = [[[NSApp mainMenu] itemAtIndex:3] submenu];
    [[viewMenu itemWithTag:MainMenu_View_GridTag] setState:NSControlStateValueOff];
    [[viewMenu itemWithTag:MainMenu_View_ListTag] setState:NSControlStateValueOn];
}

- (IBAction)search:(id)sender
{
    [[self collectionController] search:sender];
}

- (IBAction)changeGridSize:(id)sender
{
    [[self collectionController] changeGridSize:sender];
}

- (IBAction)decreaseGridSize:(id)sender
{
    NSSlider *slider = self.libraryController.toolbar.gridSizeSlider;
    slider.doubleValue -= 0.5;
    [self.collectionController changeGridSize:slider];
}

- (IBAction)increaseGridSize:(id)sender
{
    NSSlider *slider = self.libraryController.toolbar.gridSizeSlider;
    slider.doubleValue += 0.5;
    [self.collectionController changeGridSize:slider];
}

#pragma mark - Sidebar handling
- (void)_updateCollectionContentsFromSidebar:(id)sender
{
    id selectedItem = self.sidebarController.selectedSidebarItem;
    self.collectionController.representedObject = selectedItem;
    
    // For empty collections of disc-based games, display an alert to compel the user to read the disc-importing guide.
    if ([selectedItem isKindOfClass:[OEDBSystem class]] &&
        ((OEDBSystem *)selectedItem).plugin.supportsDiscsWithDescriptorFile &&
        ((OEDBSystem *)selectedItem).games.count == 0 &&
        ![[NSUserDefaults standardUserDefaults] boolForKey:OESkipDiscGuideMessageKey])
    {
        
        NSAlert *alert = [[NSAlert alloc] init];
        
        alert.messageText = NSLocalizedString(@"Have you read the guide?", @"");
        alert.informativeText = NSLocalizedString(@"Disc-based games have special requirements. Please read the disc importing guide.", @"");
        alert.alertStyle = NSAlertStyleInformational;
        [alert addButtonWithTitle:NSLocalizedString(@"View Guide in Browser", @"")];
        [alert addButtonWithTitle:NSLocalizedString(@"Dismiss", @"")];
                
        [alert beginSheetModalForWindow:self.view.window completionHandler:^(NSModalResponse returnCode) {
            if(returnCode == NSAlertFirstButtonReturn) {
                NSURL *guideURL = [NSURL URLWithString:OECDBasedGamesUserGuideURLString];
                [[NSWorkspace sharedWorkspace] openURL:guideURL];
            }
        }];
    }
}

- (void)makeNewCollectionWithSelectedGames:(id)sender
{
    OECoreDataMainThreadAssertion();
    NSArray<OEDBGame *> *selectedGames = [self selectedGames];
    OEDBCollection *collection = [[self sidebarController] addCollection:NO];
    [collection setGames:[NSSet setWithArray:selectedGames]];
    [collection save];

    [[self collectionController] setNeedsReload];
}

#pragma mark - Issue Resolving
- (IBAction)showIssuesView:(id)sender
{
    [self presentViewControllerAsSheet:self.gameScannerController];
}

@end
