//
// $Id: HPatrolToState.m,v 1.2 1997/10/31 03:38:19 nygard Exp $
//

//
//  This file is a part of Empire, a game of exploration and conquest.
//  Copyright (C) 1996  Steve Nygard
//
//  This program is free software; you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation; either version 2 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program; if not, write to the Free Software
//  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
//  You may contact the author by:
//     e-mail:  nygard@telusplanet.net
//

#import "Empire.h"

RCSID ("$Id: HPatrolToState.m,v 1.2 1997/10/31 03:38:19 nygard Exp $");

#import "HPatrolToState.h"

#import "HSMarquee.h"
#import "Human.h"
#import "Map.h"
#import "MapPathView.h"
#import "PathSegment.h"
#import "Unit.h"

#import "../Orders.subproj/Orders.h"
#import <AppKit/psopsNeXT.h>

//======================================================================
// Instruct the selected unit to patrol to the location where a mouseUp
// event is received.
//======================================================================

@implementation HPatrolToState

- initWithGameManager:(GameManager *)theGameManager
{
    [super initWithGameManager:theGameManager];

    patternOffset = 0;

    return self;
}

//======================================================================
// Subclass responsibilities
//======================================================================

- (NSString *) stateName
{
    return @"Patrol To";
}
  
//----------------------------------------------------------------------

- (NSString *) stateKey
{
    return HS_PATROL_TO;
}
  
//----------------------------------------------------------------------

- (void) stateEntered:(Human *)context
{
    MapPathView *mapView = [context mapView];
    NSMutableArray *pathList = [NSMutableArray array];
    NSArray *unitList = [context unitList];
  
    Map *map = [context map];
    Unit *unit;
    EMMapLocation unitLocation;
    MapToken mapToken;

    NSEnumerator *unitEnumerator;

    // Set cursor
    [mapView useDefaultCursor];
    [mapView setCursorEnabled:NO];
    [mapView enableCompressedEvents:NO];

    // Disable both buttons
    [context enableContinueButton:NO];
    [context enableEndTurnButton:NO];

    unit = [context selectedUnit];
    if (unit == nil)
    {
        NSBeep ();
        [context restoreState];
    }
    else
    {
        unitLocation = [unit unitLocation];
        mapToken = [map tokenAtLocation:unitLocation];

        if (EMTerrainComponent (mapToken) == t_city)
        {
            // Need to show unit on city.
            [map setToken:EMChangeIconComponent (mapToken, [unit icon]) atLocation:unitLocation];
        }

        unitEnumerator = [unitList objectEnumerator];
        
        while (unit = [unitEnumerator nextObject])
        {
            Order *order = [unit currentOrder];

            if (order != nil)
            {
                PathSegment *pathSegment = [order pathInMapView:mapView];

                if (pathSegment != nil)
                    [pathList addObject:pathSegment];
            }
        }

        [mapView usePathList:pathList];

        [self showMarquee:context atLocation:unitLocation];
    }
}
  
//----------------------------------------------------------------------

- (void) stateExited:(Human *)context
{
    [self stopMarquee:context];
}
  
//----------------------------------------------------------------------

- (void) mouseDown:(Human *)context:(unsigned int)modifierFlags atLocation:(EMMapLocation)target
{
    Unit *unit = [context selectedUnit];
    EMMapLocation unitLocation = [unit unitLocation];
    MapPathView *mapView = [context mapView];
    NSPoint a, b;
    float pat[2] = {3};
    int dr = target.row - unitLocation.row;
    int dc = target.column - unitLocation.column;
    int distance;

    [self stopMarquee:context];

    if (dr < 0)
        dr = -dr;
    if (dc < 0)
        dc = -dc;

    distance = (dr > dc) ? dr : dc;

    a = [mapView getCenterPointForLocation:unitLocation];
    b = [mapView getCenterPointForLocation:target];

    //[mapView centerCell:row:col ifNotVisible:YES];
    [mapView scrollLocationToVisible:target];

    [context setStatusLine:[NSString stringWithFormat:@"%d,%d Distance %d", target.row, target.column, distance]];

    [mapView lockFocus];
    PSsetlinewidth (3);
    PSsetdash (pat, 1, 5 - patternOffset);
    PSnewinstance ();
    PSsetinstance (YES);

    PSsetgray (NSWhite);
    PSmoveto (a.x, a.y);
    PSlineto (b.x, b.y);
    PSstroke ();
    HSDrawMarquee (a.x - 8, a.y - 7, a.x + 7, a.y + 8, 5 - patternOffset);
    PSsetinstance (NO);
    [mapView unlockFocus];

    patternOffset = (patternOffset + 1) % 6;
}

//----------------------------------------------------------------------

- (void) mouseUp:(Human *)context:(unsigned int)modifierFlags atLocation:(EMMapLocation)target
{
    MapPathView *mapView = [context mapView];
    Unit *unit = [context selectedUnit];
  
    Map *map = [context map];
    EMMapLocation unitLocation = [unit unitLocation];
    MapToken mapToken = [map tokenAtLocation:unitLocation];

    [mapView lockFocus];
    PSnewinstance ();
    [mapView unlockFocus];

    if (unitLocation.row != target.row || unitLocation.column != target.column)
    {
        Order *order;
    
        if ([unit unitType] == u_fighter && [unit isOnBoardShip] == YES)
        {
            order = [[[OPatrolFromShip alloc] initForUnit:unit patrolToLocation:target onMap:map] autorelease];
        }
        else
        {
            order = [[[OPatrolTo alloc] initForUnit:unit
                                        patrolFromLocation:unitLocation
                                        toLocation:target
                                        onMap:map] autorelease];
        }
        [unit setOrder:order];
    }

    [mapView usePathList:nil]; // This will free list and its objects.

    if (EMTerrainComponent (mapToken) == t_city)
    {
        // Need to show unit on city.
        [map setToken:EMChangeIconComponent (mapToken, i_none) atLocation:unitLocation];
    }

    [context restoreState];
}

//----------------------------------------------------------------------

- (void) keyDown:(Human *)context:(NSEvent *)theEvent
{
    NSString *eventCharacters = [theEvent characters];
    unichar uc = [eventCharacters characterAtIndex:0];

    switch (uc)
    {
      case 27: // Escape key
      case ' ':
          [context restoreState];
          break;
 
      default:
          [super keyDown:context:theEvent];
          break;
   }
}

@end
