/*
SRSecurityPref.m

Author: Makoto Kinoshita

Copyright 2004-2006 The Shiira Project. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted 
provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions 
  and the following disclaimer.

  2. 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.

THIS SOFTWARE IS PROVIDED BY THE SHIIRA PROJECT ``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 THE SHIIRA PROJECT OR CONTRIBUTORS 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 "SRAutoFillManager.h"

#import "SRSecurityPref.h"
#import "SRPrefDefaultKeys.h"

@interface SRCookiesProxy : NSMutableArray
// Initialize
+ (id)sharedInstance;
@end

@implementation SRCookiesProxy

//--------------------------------------------------------------//
#pragma mark -- Initialize --
//--------------------------------------------------------------//

+ (id)sharedInstance
{
    static SRCookiesProxy*  _sharedInstance = nil;
    if (!_sharedInstance) {
        _sharedInstance = [[SRCookiesProxy alloc] init];
    }
    
    return _sharedInstance;
}

//--------------------------------------------------------------//
#pragma mark -- NSArray primitive --
//--------------------------------------------------------------//

- (unsigned)count
{
    return [[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies] count];
}

- (id)objectAtIndex:(unsigned)index
{
    return [[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies] objectAtIndex:index];
}

//--------------------------------------------------------------//
#pragma mark -- NSMutableArray primitive --
//--------------------------------------------------------------//

- (void)addObject:(id)anObject
{
    // Do nothing
}

- (void)insertObject:(id)anObject atIndex:(unsigned)index
{
    // Do nothing
}

- (void)removeLastObject
{
    // Delete last cookie
    NSHTTPCookieStorage*    storage;
    NSHTTPCookie*           lastCookie;
    storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    lastCookie = [[storage cookies] lastObject];
    [storage deleteCookie:lastCookie];
}

- (void)removeObjectAtIndex:(unsigned)index
{
    // Delete cookie at index
    NSHTTPCookieStorage*    storage;
    NSHTTPCookie*           cookie;
    storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    cookie = [[storage cookies] objectAtIndex:index];
    [storage deleteCookie:cookie];
}

- (void)replaceObjectAtIndex:(unsigned)index withObject:(id)object
{
    // Do nothing
}

@end

#pragma mark -

@interface SRUserPassProxy : NSMutableArray
// Initialize
+ (id)sharedInstance;
@end

@implementation SRUserPassProxy

//--------------------------------------------------------------//
#pragma mark -- Initialize --
//--------------------------------------------------------------//

+ (id)sharedInstance
{
    static SRUserPassProxy* _sharedInstance = nil;
    if (!_sharedInstance) {
        _sharedInstance = [[SRUserPassProxy alloc] init];
    }
    
    return _sharedInstance;
}

//--------------------------------------------------------------//
#pragma mark -- NSArray primitive --
//--------------------------------------------------------------//

- (unsigned)count
{
    return [[[SRAutoFillManager sharedInstance] formContents] count];
}

- (id)objectAtIndex:(unsigned)index
{
    // Get form contents
    NSDictionary*   formContents;
    formContents = [[SRAutoFillManager sharedInstance] formContents];
    
    // Get key
    NSString*   key;
    key = [[formContents allKeys] objectAtIndex:index];
    
    // Get user name
    NSString*   userName = @"";
    NSArray*    textInputNodes;
    textInputNodes = [[formContents objectForKey:key] objectForKey:@"textInputNodeDicts"];
    if ([textInputNodes count] > 0) {
        NSMutableString*    buffer;
        buffer = [NSMutableString string];
        
        int i;
        for (i = 0; i < [textInputNodes count]; i++) {
            NSDictionary*   textInputNode;
            textInputNode = [textInputNodes objectAtIndex:i];
            
            // Get value
            NSString*   value;
            value = [textInputNode objectForKey:@"value"];
            if (value && [value length] > 0) {
                if ([buffer length] > 0) {
                    [buffer appendString:@", "];
                }
                [buffer appendString:value];
            }
        }
        
        userName = buffer;
    }
    
    return [NSDictionary dictionaryWithObjectsAndKeys:
            key, @"url", 
            userName, @"userName", 
            nil];
}

//--------------------------------------------------------------//
#pragma mark -- NSMutableArray primitive --
//--------------------------------------------------------------//

- (void)addObject:(id)anObject
{
    // Do nothing
}

- (void)insertObject:(id)anObject atIndex:(unsigned)index
{
    // Do nothing
}

- (void)removeLastObject
{
}

- (void)removeObjectAtIndex:(unsigned)index
{
}

- (void)replaceObjectAtIndex:(unsigned)index withObject:(id)object
{
    // Do nothing
}

@end

#pragma mark -

@implementation SRSecurityPref

//--------------------------------------------------------------//
#pragma mark -- Cookie --
//--------------------------------------------------------------//

- (NSHTTPCookieStorage*)cookieStorage
{
    return [NSHTTPCookieStorage sharedHTTPCookieStorage];
}

- (NSMutableArray*)cookies
{
    return [SRCookiesProxy sharedInstance];
}

- (void)setCookies:(NSMutableArray*)cookies
{
    // Delete cookies
    NSMutableArray* currentCookies;
    NSMutableArray* deletedCookies;
    NSEnumerator*   enumerator;
    id              cookie;
    currentCookies = [self cookies];
    deletedCookies = [NSMutableArray array];
    enumerator = [currentCookies objectEnumerator];
    while (cookie = [enumerator nextObject]) {
        if ([cookies indexOfObjectIdenticalTo:cookie] == NSNotFound) {
            [deletedCookies addObject:cookie];
        }
    }
    
    [currentCookies removeObjectsInArray:deletedCookies];
}

//--------------------------------------------------------------//
#pragma mark -- User and pass --
//--------------------------------------------------------------//

- (NSMutableArray*)userPass
{
    return [SRUserPassProxy sharedInstance];
}

//--------------------------------------------------------------//
#pragma mark -- Action --
//--------------------------------------------------------------//

- (void)openCookiePanelAction:(id)sender
{
    // Rearrange cookies
    [_cookieArrayController rearrangeObjects];
    
    // Open cookie panel
    [NSApp beginSheet:_cookiePanel 
            modalForWindow:[_mainView window] 
            modalDelegate:self 
            didEndSelector:@selector(cookiePanelDidEnd:returnCode:contextInfo:) 
            contextInfo:NULL];
}

- (void)cookiePanelDidEnd:(NSWindow*)sheet 
        returnCode:(int)returnCode contextInfo:(void*)contextInfo
{
    // Close sheet
    [_cookiePanel orderOut:self];
}

- (void)closeCookiePanelAction:(id)sender
{
    // End sheet
    [NSApp endSheet:_cookiePanel returnCode:[sender tag]];
}

- (void)openUserPassPanelAction:(id)sender
{
    // Rearrange user pass
    [_userPassArrayController rearrangeObjects];
    
    // Open user pass panel
    [NSApp beginSheet:_userPassPanel 
            modalForWindow:[_mainView window] 
            modalDelegate:self 
            didEndSelector:@selector(userPassPanelDidEnd:returnCode:contextInfo:) 
            contextInfo:NULL];
}

- (void)userPassPanelDidEnd:(NSWindow*)sheet 
        returnCode:(int)returnCode contextInfo:(void*)contextInfo
{
    // Close sheet
    [_userPassPanel orderOut:self];
}

- (void)closeUserPassPanelAction:(id)sender
{
    // End sheet
    [NSApp endSheet:_userPassPanel returnCode:[sender tag]];
}

- (void)openKeychainAction:(id)sender
{
    [[NSWorkspace sharedWorkspace] launchApplication:@"Keychain Access"];
}

@end
