/*
 *  Author:       Serg Stoyan
 *
 *  Classes:      ConnectionView : NSObject <PrefsViewProtocol>
 *
 *  Description:  Connection preferences (name, run on startup, phones, etc.)
 */

#import <AppKit/NSView.h>
#import <AppKit/NSWindow.h>
#import <AppKit/NSBox.h>
#import <AppKit/NSButton.h>
#import <AppKit/NSTextField.h>
#import <AppKit/NSPopUpButton.h>
#import <AppKit/NSImage.h>
#import <AppKit/NSScrollView.h>
#import <AppKit/NSTableView.h>
#import <AppKit/NSTableColumn.h>
#import <AppKit/NSOpenPanel.h>

#import "Connection.h"

@implementation ConnectionView

- (id) initWithPrefs: (NSMutableDictionary *) sessionPrefs
{
  NSView *phonesFrameView;
  NSView *actionsFrameView;
  NSView *runFrameView;

  [super init];

  prefs = [sessionPrefs objectForKey: @"Connection"];

  view = [[NSView alloc] initWithFrame: NSMakeRect (10, 44, 280, 393)];

  // Connection Name
  nameLabel = [[NSTextField alloc] initWithFrame: 
    NSMakeRect (0, 366, 103, 21)];
  [nameLabel setAlignment: NSRightTextAlignment];
  [nameLabel setBackgroundColor: [NSColor windowBackgroundColor]];
  [nameLabel setSelectable: NO];
  [nameLabel setEditable: NO];
  [nameLabel setBezeled: NO];
  [nameLabel setBordered: NO];
  [nameLabel setStringValue: @"Session name"];
  [view addSubview: nameLabel];
  
  nameTF = [[NSTextField alloc] initWithFrame: 
    NSMakeRect (108, 366, 172, 21)];
  [nameTF setDelegate: self];
  [nameTF setStringValue: [prefs objectForKey: @"ConnectionName"]];
  [view addSubview: nameTF];

  // Connection Type
  typeLabel = [[NSTextField alloc] initWithFrame: 
    NSMakeRect (0, 340, 103, 21)];
  [typeLabel setAlignment: NSRightTextAlignment];
  [typeLabel setBackgroundColor: [NSColor windowBackgroundColor]];
  [typeLabel setSelectable: NO];
  [typeLabel setEditable: NO];
  [typeLabel setBezeled: NO];
  [typeLabel setBordered: NO];
  [typeLabel setStringValue: @"Connection type"];
  [view addSubview: typeLabel];
  
  typePop = [[NSPopUpButton alloc] initWithFrame:
    NSMakeRect (108, 340, 172, 21)];
  [typePop setAutoenablesItems: NO];
  [typePop addItemWithTitle: @"Connect session"];
  [typePop addItemWithTitle: @"Script or program"];
  [typePop setAction: @selector (typePopAction:)];
  [typePop setTarget: self];
  [view addSubview: typePop];

  // Phone nubmers -------------------------------------------------- 
  phonesFrame = [[NSBox alloc] initWithFrame:
    NSMakeRect (0, 210, 280, 125)];
  [phonesFrame setTitle: @"Phone numbers"];
//  [view addSubview: phonesFrame];
  phonesFrameView = [phonesFrame contentView];

  // Table
  phonesArray = RETAIN ([NSMutableArray array]);

  phonesScroll = [[NSScrollView alloc] initWithFrame:
    NSMakeRect (0, 0, 201, 99)];

  phonesColumn = [[NSTableColumn alloc] initWithIdentifier: @"Phones List"];
  [phonesColumn setEditable: YES];

  phonesList = [[NSTableView alloc] initWithFrame:
    NSMakeRect (0, 0, 201, 99)];
  [phonesList setCornerView: nil];
  [phonesList setHeaderView: nil];
  [phonesList addTableColumn: phonesColumn];
  [phonesList setDataSource: self];

  [phonesScroll setDocumentView: phonesList];
  [phonesScroll setHasHorizontalScroller: NO];
  [phonesScroll setHasVerticalScroller: YES];
  [phonesScroll setBorderType: NSBezelBorder];
  
  [phonesFrameView addSubview: phonesScroll];

  // Buttons
  addPhoneButton = [[NSButton alloc] initWithFrame: 
    NSMakeRect (206, 78, 60, 21)];
  [addPhoneButton setButtonType: NSMomentaryPushButton];
  [addPhoneButton setTitle: @"Add"];
  [addPhoneButton setAction: @selector (addPhoneAction)];
  [addPhoneButton setTarget: self];
  [phonesFrameView addSubview: addPhoneButton];
  
  removePhoneButton = [[NSButton alloc] initWithFrame: 
    NSMakeRect (206, 52, 60, 21)];
  [removePhoneButton setButtonType: NSMomentaryPushButton];
  [removePhoneButton setTitle: @"Remove"];
  [removePhoneButton setAction: @selector (removePhoneAction)];
  [removePhoneButton setTarget: self];
  [phonesFrameView addSubview: removePhoneButton];
  
  upPhoneButton = [[NSButton alloc] initWithFrame: 
    NSMakeRect (206, 26, 60, 21)];
  [upPhoneButton setButtonType: NSMomentaryPushButton];
  [upPhoneButton setImagePosition: NSImageOnly];
  [upPhoneButton setImage: [NSImage imageNamed: @"common_ArrowUp"]];
  [upPhoneButton setAction: @selector (upPhoneAction)];
  [upPhoneButton setTarget: self];
  [phonesFrameView addSubview: upPhoneButton];

  downPhoneButton = [[NSButton alloc] initWithFrame: 
    NSMakeRect (206, 0, 60, 21)];
  [downPhoneButton setButtonType: NSMomentaryPushButton];
  [downPhoneButton setImagePosition: NSImageOnly];
  [downPhoneButton setImage: [NSImage imageNamed: @"common_ArrowDown"]];
  [downPhoneButton setAction: @selector (downPhoneAction)];
  [downPhoneButton setTarget: self];
  [phonesFrameView addSubview: downPhoneButton];

  // Actions -------------------------------------------------- 
  actionsFrame = [[NSBox alloc] initWithFrame:
    NSMakeRect (0, 108, 280, 99)];
  [actionsFrame setTitle: @"Actions"];
//  [view addSubview: actionsFrame];
  actionsFrameView = [actionsFrame contentView];

  // On Connect run
  onConnectLabel = [[NSTextField alloc] initWithFrame: 
    NSMakeRect (0, 52, 110, 21)];
  [onConnectLabel setAlignment: NSRightTextAlignment];
  [onConnectLabel setBackgroundColor: [NSColor windowBackgroundColor]];
  [onConnectLabel setSelectable: NO];
  [onConnectLabel setEditable: NO];
  [onConnectLabel setBezeled: NO];
  [onConnectLabel setBordered: NO];
  [onConnectLabel setStringValue: @"On connect run"];
  [actionsFrameView addSubview: onConnectLabel];
  
  onConnectTF = [[NSTextField alloc] initWithFrame: 
    NSMakeRect (115, 52, 151, 21)];
  [actionsFrameView addSubview: onConnectTF];

  // On Disconnect run
  onDisconnectLabel = [[NSTextField alloc] initWithFrame: 
    NSMakeRect (0, 26, 110, 21)];
  [onDisconnectLabel setAlignment: NSRightTextAlignment];
  [onDisconnectLabel setBackgroundColor: [NSColor windowBackgroundColor]];
  [onDisconnectLabel setSelectable: NO];
  [onDisconnectLabel setEditable: NO];
  [onDisconnectLabel setBezeled: NO];
  [onDisconnectLabel setBordered: NO];
  [onDisconnectLabel setStringValue: @"On disconnect run"];
  [actionsFrameView addSubview: onDisconnectLabel];
  
  onDisconnectTF = [[NSTextField alloc] initWithFrame: 
    NSMakeRect (115, 26, 151, 21)];
  [actionsFrameView addSubview: onDisconnectTF];
  
  // Disconnect After
  idleLabel = [[NSTextField alloc] initWithFrame: 
    NSMakeRect (0, 0, 110, 21)];
  [idleLabel setAlignment: NSRightTextAlignment];
  [idleLabel setBackgroundColor: [NSColor windowBackgroundColor]];
  [idleLabel setSelectable: NO];
  [idleLabel setEditable: NO];
  [idleLabel setBezeled: NO];
  [idleLabel setBordered: NO];
  [idleLabel setStringValue: @"Disconnect after"];
  [actionsFrameView addSubview: idleLabel];
  
  idleTF = [[NSTextField alloc] initWithFrame: 
    NSMakeRect (115, 0, 56, 21)];
  [actionsFrameView addSubview: idleTF];

  secondsLabel = [[NSTextField alloc] initWithFrame: 
    NSMakeRect (176, 0, 90, 21)];
  [secondsLabel setAlignment: NSRightTextAlignment];
  [secondsLabel setBackgroundColor: [NSColor windowBackgroundColor]];
  [secondsLabel setSelectable: NO];
  [secondsLabel setEditable: NO];
  [secondsLabel setBezeled: NO];
  [secondsLabel setBordered: NO];
  [secondsLabel setStringValue: @"seconds of idle"];
  [actionsFrameView addSubview: secondsLabel];

  // Linking TFs
  [onConnectTF setNextText: onDisconnectTF];
  [onDisconnectTF setNextText: idleTF];
  [idleTF setNextText: onConnectTF];

  // Advanced button
  advancedButton = [[NSButton alloc] initWithFrame: 
    NSMakeRect (198, 70, 82, 24)];
  [advancedButton setButtonType: NSMomentaryPushButton];
  [advancedButton setTitle: @"Advanced..."];
  [advancedButton setAction: @selector (advancedButtonAction)];
  [advancedButton setTarget: self];
//  [view addSubview: advancedButton];

  // "Script or program" type of connection --------------------------- 
  runFrame = [[NSBox alloc] initWithFrame:
    NSMakeRect (0, 288, 280, 47)];
  [runFrame setTitle: @"Script or program to run"];
//  [view addSubview: runFrame];
  runFrameView = [runFrame contentView];

  runTF = [[NSTextField alloc] initWithFrame: 
    NSMakeRect (0, 0, 196, 21)];
  [runTF setDelegate: self];
  [runFrameView addSubview: runTF];

  // Browse button
  runBrowseButton = [[NSButton alloc] initWithFrame: 
    NSMakeRect (201, 0, 65, 21)];
  [runBrowseButton setButtonType: NSMomentaryPushButton];
  [runBrowseButton setTitle: @"Browse..."];
  [runBrowseButton setAction: @selector (runBrowseButtonAction)];
  [runBrowseButton setTarget: self];
  [runFrameView addSubview: runBrowseButton];

  RELEASE (nameLabel);
  RELEASE (nameTF);
  RELEASE (typeLabel);
  RELEASE (typePop);

  RELEASE (phonesScroll);
  RELEASE (phonesList);
  RELEASE (phonesColumn);
  RELEASE (addPhoneButton);
  RELEASE (removePhoneButton);
  RELEASE (upPhoneButton);
  RELEASE (downPhoneButton);
//  RELEASE (phonesFrame);

  RELEASE (onConnectLabel);
  RELEASE (onConnectTF);
  RELEASE (onDisconnectLabel);
  RELEASE (onDisconnectTF);
  RELEASE (idleLabel);
  RELEASE (idleTF);
  RELEASE (secondsLabel);
//  RELEASE (actionsFrame);
  
  RELEASE (runTF);
  RELEASE (runBrowseButton);
//  RELEASE (runFrame);

//  RELEASE (advancedButton);

  // load settings or set defaults
  [self setDefaults];

  return self;
}

// dealloc never called for array memebers
- (void) release
{
  NSLog (@"ConnectionView: release (%i)", [view retainCount]);
  if ([view superview])
  {
    [view removeFromSuperview];
  }
  else
  {
    RELEASE (view);
  }

  [super dealloc];
}

/*-------------------------------------------------------------------------*
 *  Protocol methods
 *-------------------------------------------------------------------------*/
- (id) show: (id)superView
{
  [superView addSubview: view];
  RELEASE (view);
  [self typePopAction: self];

  return nameTF;
}

- (void) hide 
{
  RETAIN (view);
  [view removeFromSuperview];
}

- (void) setDefaults
{
  currentType = [[NSString alloc] initWithString: @""];

  if ([prefs count] > 1) // ConnectionName is always here
  {
    [typePop selectItemWithTitle: [prefs objectForKey: @"ConnectionType"]];
    [phonesArray setArray: [prefs objectForKey: @"PhoneNumbers"]];
    [phonesList reloadData];
    [onConnectTF setStringValue: [prefs objectForKey: @"RunOnConnect"]];
    [onDisconnectTF setStringValue: [prefs objectForKey: @"RunOnDisconnect"]];
    [idleTF setStringValue: [prefs objectForKey: @"Idle"]];

    [runTF setStringValue: [prefs objectForKey: @"ScriptOrProgram"]];
  }
  else
  {
    [idleTF setStringValue: @"300"];
  }
//  [self typePopAction: self];
//  [self defaultButtonAction: self];
}

- (NSMutableDictionary *) prefsDict
{
  [prefs setObject: [nameTF stringValue] forKey: @"ConnectionName"];
  [prefs setObject: [typePop titleOfSelectedItem] forKey: @"ConnectionType"];
  if ([[typePop titleOfSelectedItem] isEqualToString: @"Script or program"])
  {
    [prefs setObject: [runTF stringValue] forKey: @"ScriptOrProgram"];
  }
  else
  {
    [prefs setObject: phonesArray forKey: @"PhoneNumbers"];
    [prefs setObject: [onConnectTF stringValue] forKey: @"RunOnConnect"];
    [prefs setObject: 
      [onDisconnectTF stringValue] forKey: @"RunOnDisconnect"];
    [prefs setObject: [idleTF stringValue] forKey: @"Idle"];
  }

  return prefs;
}

/*-------------------------------------------------------------------------*
 *  Controls' action methods
 *-------------------------------------------------------------------------*/
- (void) typePopAction: (id)sender
{
  NSString *selectedItem = [typePop titleOfSelectedItem];

  if ([currentType compare: selectedItem] != NSOrderedSame)
  {
    if ([selectedItem isEqualToString: @"Script or program"])
    {
      NSLog (@"Script or program");
      if([phonesFrame superview]) // remove "Connect session" controls
      {
        RETAIN (phonesFrame);
        RETAIN (actionsFrame);
        RETAIN (advancedButton);
        [phonesFrame removeFromSuperview];
        [actionsFrame removeFromSuperview];
        [advancedButton removeFromSuperview];
      }
      
      if ([runFrame superview] == nil)
      {
        [view addSubview: runFrame];
        RELEASE (runFrame);
      }

      [self setSectionsStatus: NO 
        forPopUp: [[view superview] viewWithTag: 10]];
    }
    else // "Connect session"
    {
      if ([runFrame superview])
      {
        RETAIN (runFrame);
        [runFrame removeFromSuperview];
      }
      if([phonesFrame superview] == nil)
      {
        [view addSubview: phonesFrame];
        [view addSubview: actionsFrame];
        [view addSubview: advancedButton];
        RELEASE (phonesFrame);
        RELEASE (actionsFrame);
        RELEASE (advancedButton);
      }

      [self setSectionsStatus: YES
        forPopUp: [[view superview] viewWithTag: 10]];
    }

    RELEASE (currentType);
    currentType = [[NSString alloc] initWithString: selectedItem];
  }

  RELEASE (selectedItem);
}

- (void) setSectionsStatus: (BOOL)enable 
                  forPopUp: (NSPopUpButton *)popup
{
  int        numberOfSections = [popup numberOfItems];
  int        i;
  NSArray    *sections = [popup itemArray];
  NSMenuItem *item;

  for (i = 1; i < numberOfSections; i++)
  {
    item = [sections objectAtIndex: i];
    if (![[item title] isEqualToString: @"Connection"])
    {
      [item setEnabled: enable];
    }
  }
}

- (BOOL)      control:(NSControl *)control
 textShouldEndEditing:(NSText *)textObject
{
  NSString *enteredText = [nameTF stringValue];
  NSWindow *prefsPanel = [[view superview] window];

  if (![enteredText length])
  {
/*    NSRunAlertPanel(@"Session Preferences", 
        @"You have to enter session name first",
        @"Ok", nil, nil);
    return NO;*/
    return YES;
  }

  [prefsPanel setTitle: 
    [NSString stringWithFormat: @"%@ - Session Inspector", enteredText]];

  return YES;
}

// Table of Phones Numbers
- (void) addPhoneAction 
{
  int row;
  
  [phonesArray addObject: [NSMutableString stringWithString: @""]];
  [phonesList reloadData];

  row = [phonesArray count] - 1;
  [phonesList selectRow: row byExtendingSelection: NO];
  [phonesList editColumn: 0 row: row  withEvent: nil select: YES];
}

- (void) removePhoneAction 
{
  int selectedRow = [phonesList selectedRow];

  if (selectedRow >= 0)
  {
    [phonesArray removeObjectAtIndex: [phonesList selectedRow]];
    [phonesList reloadData];
  }

  if ([phonesList selectedRow] < 0 && [phonesArray count] > 0)
  {
    [phonesList selectRow: [phonesArray count]-1 byExtendingSelection: NO];
  }
}

- (void) upPhoneAction 
{
  int selectedRow = [phonesList selectedRow];
  id  previousRow;
  id  currentRow;

  if (selectedRow > 0)
  {
    previousRow = [[phonesArray objectAtIndex: selectedRow-1] copy];
    currentRow = [phonesArray objectAtIndex: selectedRow];
    
    [phonesArray replaceObjectAtIndex: selectedRow-1 withObject: currentRow];
    [phonesArray replaceObjectAtIndex: selectedRow withObject: previousRow];
      
    [phonesList selectRow: selectedRow-1 byExtendingSelection: NO];
    
    [phonesList reloadData];
  }
}

- (void) downPhoneAction 
{
  int selectedRow = [phonesList selectedRow];
  id  nextRow;
  id  currentRow;

  if (selectedRow < [phonesArray count]-1)
  {
    nextRow = [[phonesArray objectAtIndex: selectedRow+1] copy];
    currentRow = [phonesArray objectAtIndex: selectedRow];
    
    [phonesArray replaceObjectAtIndex: selectedRow+1 withObject: currentRow];
    [phonesArray replaceObjectAtIndex: selectedRow withObject: nextRow];
      
    [phonesList selectRow: selectedRow+1 byExtendingSelection: NO];
    
    [phonesList reloadData];
  }
}

- (void) advancedButtonAction
{
  NSRunAlertPanel(@"Session Preferences", 
      @"Sorry, adnvanced connection setting is not implemented yet",
      @"Ok", nil, nil);
}

- (void) runBrowseButtonAction
{
  NSOpenPanel *openPanel = [NSOpenPanel openPanel];
  int         result;

  [openPanel setAllowsMultipleSelection: NO];
  [openPanel setCanChooseDirectories: NO];
  result = [openPanel runModalForDirectory: @"/" file: nil types: nil];

  if (result == NSOKButton)
  {
    [runTF setStringValue: [[openPanel filenames] objectAtIndex: 0]];
  }
}

- (int)numberOfRowsInTableView: (NSTableView *)aTableView
{
  return [phonesArray count];
}

- (id)            tableView: (NSTableView *)aTableView
  objectValueForTableColumn: (NSTableColumn *)aTableColumn
                        row: (int)rowIndex
{
  return [phonesArray objectAtIndex: rowIndex];
}

- (void) tableView: (NSTableView *)aTableView
    setObjectValue: anObject
    forTableColumn: (NSTableColumn *)aTableColumn
               row: (int)rowIndex
{
  NSParameterAssert (rowIndex >= 0 && rowIndex < [phonesArray count]);

  [phonesArray removeObjectAtIndex: rowIndex];
  [phonesArray insertObject: anObject atIndex: rowIndex];
}

@end
