/*
    RelativePathUtilities.m

    Implementations of extensions to the NSString class to provide
    relative path handling.

    Authors: Matt Rice  <ratmice@yahoo.com>
             Saso Kiselkov  <diablos@manga.sk>

    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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#import "RelativePathUtilities.h"

#import <Foundation/NSArray.h>
#import <Foundation/NSBundle.h>
#import <Foundation/NSException.h>

@implementation NSString (RelativePathUtilities)

/**
 * Builds a relative path from the path represented by the
 * receiver to the path in `otherPath'.
 *
 * @return The resulting relative path.
 */
- (NSString *) stringByConstructingRelativePathTo: (NSString *) otherPath
{
  NSString *prefix = [self commonPrefixWithString: otherPath
                                          options: NSLiteralSearch];
  NSRange rng1 = [otherPath rangeOfString: prefix];

  NSRange rng2 = [self rangeOfString: prefix];
  NSString *newPath = @"";
  NSString *tmp1;
  NSString *tmp2;
  NSArray *arr2;
  int i, c;

  tmp1 = [otherPath substringFromIndex: rng1.location + rng1.length];
  tmp2 = [self substringFromIndex: rng2.location + rng2.length];

  arr2 = [tmp2 pathComponents];
  
  for (i = 0, c = [arr2 count]; i < c; i++)
    {
      newPath = [newPath stringByAppendingPathComponent: @".."];
    }

  if ([tmp1 isAbsolutePath])
    {
      tmp1 = [@"." stringByAppendingString: tmp1];
    }

  return [newPath stringByAppendingPathComponent: tmp1];
}

/**
 * Builds a minimalized path which results when the path
 * represented by the receiver and `otherPath' are concatenated.
 * For example, let the receiver be @"/foo/bar" and
 * otherPath = @"../foobar". Then the returned result would be
 * @"/foo/foobar". In case `otherPath' is an absolute path, this
 * method simply returns `otherPath'.
 *
 * @return The concatenated and minimized result path.
 */
- (NSString *) stringByConcatenatingWithPath: (NSString *) otherPath
{
  if ([otherPath isAbsolutePath])
    {
      return otherPath;
    }
  else
    {
      BOOL isAbsolute = [self isAbsolutePath];
      NSMutableArray * myPathComponents = [[[self pathComponents]
        mutableCopy] autorelease];
      NSArray * otherPathComponents = [otherPath pathComponents];
      NSEnumerator * e = [otherPathComponents objectEnumerator];
      NSString * pathComponent;

      while ((pathComponent = [e nextObject]) != nil)
        {
          if ([pathComponent isEqualToString: @".."])
            {
              int numberOfComponents = [myPathComponents count];

              /* if we've run out of path components to pop away,
                 then we may safely return the rest of the relative
                 path given as the argument */
              if (numberOfComponents == 0)
                {
                  do {
                    [myPathComponents addObject: pathComponent];
                  } while ((pathComponent = [e nextObject]) != nil);

                  return [NSString pathWithComponents: myPathComponents];
                }
              /* trouble - we are an absolute path, but the argument
                 relative path wants ascend above our root. How do
                 we best handle this case? For now, we simply ignore
                 further ".." components, behaving exactly like a UNIX
                 system behaves when somebody tries to ascend above
                 the root of the VFS. */
              else if (numberOfComponents == 1 && isAbsolute == YES)
                {
                  continue;
                }
              else
                {
                  [myPathComponents removeLastObject];
                }
            }
          else
            {
              [myPathComponents addObject: pathComponent];
            }
        }

      // this is to make +[NSString pathWithComponents:] construct
      // an absolute path if necessary
      if (isAbsolute == YES)
        {
          [myPathComponents replaceObjectAtIndex: 0 withObject: @""];
        }

      return [NSString pathWithComponents: myPathComponents];
    }
}

@end
