/*  -*-objc-*-
 *  RpmViewer.m 
 *
 *  Copyright (c) 2002 Fabien VALLON <fabien.vallon@fr.alcove.com>
 *  
 *  Author: Fabien VALLON <fabien.vallon@fr.alcove.com>
 *  Date: August 2002
 *
 *  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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
#include "RpmViewer.h"

@implementation RpmViewer

- (void)dealloc
{
  TEST_RELEASE( resultPackageName);
  TEST_RELEASE( resultPackageMaintainer);
  TEST_RELEASE( resultPackageVersion);
  TEST_RELEASE( resultPackageUrl);
  TEST_RELEASE( resultPackageSize);
  TEST_RELEASE( resultPackageDescription);
  RELEASE(extsarr);
  RELEASE(rpmFilesArray);
  [super dealloc];
}

- (id)initWithFrame:(NSRect)frameRect
          inspector:(id)insp
{
	self = [super initWithFrame: frameRect];

  if(self) {
//    index = idx;
    workspace = [NSWorkspace sharedWorkspace];
    inspector = insp;

    NSString *suffs = @"rpm";
    extsarr = [[NSArray alloc] initWithArray: [suffs componentsSeparatedByString:@", "]];

    NSTextField *labelPackageMaintainer,*labelPackageVersion;
    NSTextField *labelPackageUrl,*labelPackageSize;      


    resultPackageName = [[NSTextField alloc] initWithFrame: NSMakeRect(0,220,250,25)];
    [resultPackageName setEditable : NO];
    [resultPackageName setSelectable : NO];
    [resultPackageName setAlignment:NSCenterTextAlignment];
    [resultPackageName setFont:[NSFont systemFontOfSize: 18]];
    [resultPackageName setBackgroundColor : [NSColor windowBackgroundColor]];
    [resultPackageName setBezeled: NO];

    resultPackageDescription = [[NSTextView alloc] initWithFrame: NSMakeRect(0,170,250,50)];
    [resultPackageDescription setBackgroundColor:[NSColor windowBackgroundColor]];


    //Version
    labelPackageVersion = [[NSTextField alloc] initWithFrame: NSMakeRect(0,140,60,20)];
    [labelPackageVersion setEditable : NO];
    [labelPackageVersion setSelectable : NO];
    [labelPackageVersion setAlignment:NSLeftTextAlignment];
    [labelPackageVersion setStringValue: @"Version: "];
    [labelPackageVersion setBackgroundColor : [NSColor windowBackgroundColor]];
    [labelPackageVersion setBezeled: NO];
    
    resultPackageVersion = [[NSTextField alloc] initWithFrame: NSMakeRect(60,140,190,20)];
    [resultPackageVersion setEditable : NO];
    [resultPackageVersion setSelectable : NO];
    [resultPackageVersion setAlignment:NSLeftTextAlignment];
    [resultPackageVersion setBackgroundColor : [NSColor windowBackgroundColor]];
    [resultPackageVersion setBezeled: NO];

    //Size
    labelPackageSize = [[NSTextField alloc] initWithFrame: NSMakeRect(0,110,60,20)];
    [labelPackageSize setEditable : NO];
    [labelPackageSize setSelectable : NO];
    [labelPackageSize setAlignment:NSLeftTextAlignment];
    [labelPackageSize setStringValue: @"Size: "];
    [labelPackageSize setBackgroundColor : [NSColor windowBackgroundColor]];
    [labelPackageSize setBezeled: NO];
    
    resultPackageSize = [[NSTextField alloc] initWithFrame: NSMakeRect(35,110,190,20)];
    [resultPackageSize setEditable : NO];
    [resultPackageSize setSelectable : NO];
    [labelPackageSize setAlignment:NSLeftTextAlignment];
    [resultPackageSize setBackgroundColor : [NSColor windowBackgroundColor]];
    [resultPackageSize setBezeled: NO];

    //Maintenair
    labelPackageMaintainer = [[NSTextField alloc] initWithFrame: NSMakeRect(0,80,70,20)];
    [labelPackageMaintainer setEditable : NO];
    [labelPackageMaintainer setSelectable : NO];
    [labelPackageMaintainer setAlignment:NSLeftTextAlignment];
    [labelPackageMaintainer setStringValue: @"Maintainer: "];
    [labelPackageMaintainer setBackgroundColor : [NSColor windowBackgroundColor]];
    [labelPackageMaintainer setBezeled: NO];
    
    resultPackageMaintainer = [[NSTextField alloc] initWithFrame: NSMakeRect(75,80,169,20)];
    [resultPackageMaintainer setEditable : NO];
    [resultPackageMaintainer setSelectable : NO];
    [labelPackageMaintainer setAlignment:NSLeftTextAlignment];
    [resultPackageMaintainer setBackgroundColor : [NSColor windowBackgroundColor]];
    [resultPackageMaintainer setBezeled: NO];


    //Maintenair
    labelPackageUrl = [[NSTextField alloc] initWithFrame: NSMakeRect(0,50,60,20)];
    [labelPackageUrl setEditable : NO];
    [labelPackageUrl setSelectable : NO];
    [labelPackageUrl setAlignment:NSLeftTextAlignment];
    [labelPackageUrl setStringValue: @"WebSite: "];
    [labelPackageUrl setBackgroundColor : [NSColor windowBackgroundColor]];
    [labelPackageUrl setBezeled: NO];
    
    resultPackageUrl = [[NSTextField alloc] initWithFrame: NSMakeRect(65,50,190,20)];
    [resultPackageUrl setEditable : NO];
    [resultPackageUrl setSelectable : NO];
    [labelPackageUrl setAlignment:NSLeftTextAlignment];
    [resultPackageUrl setBackgroundColor : [NSColor windowBackgroundColor]];
    [resultPackageUrl setBezeled: NO];

    [self addSubview: resultPackageName];
    [self addSubview: resultPackageDescription]; 
    [self addSubview: labelPackageVersion];
    [self addSubview: resultPackageVersion];
    [self addSubview: labelPackageMaintainer];
    [self addSubview: resultPackageMaintainer];
    [self addSubview: labelPackageUrl];
    [self addSubview: resultPackageUrl];
    [self addSubview: labelPackageSize];
    [self addSubview: resultPackageSize];

    editButt = [[NSButton alloc] initWithFrame: NSMakeRect(141, 10, 115, 25)];
    [editButt setButtonType: NSMomentaryLight];
    [editButt setImage: [NSImage imageNamed: @"common_ret.tiff"]];
    [editButt setImagePosition: NSImageRight];
    [editButt setTitle: NSLocalizedString(@"Edit", @"")];
    [editButt setTarget: self];
    [editButt setAction: @selector(editFile:)];	
    [editButt setEnabled: NO];		
    [self addSubview: editButt]; 
    RELEASE (editButt);

        //label if error
    errorLabel = [[NSTextField alloc] initWithFrame: NSMakeRect(0, 0, 250, 240)];	
    [errorLabel setFont: [NSFont systemFontOfSize: 18]];
    [errorLabel setAlignment: NSCenterTextAlignment];
    [errorLabel setBackgroundColor: [NSColor windowBackgroundColor]];
    [errorLabel setTextColor: [NSColor grayColor]];	
    [errorLabel setBezeled: NO];
    [errorLabel setEditable: NO];
    [errorLabel setSelectable: NO];
  }
  return self;
}

- (void)displayPath:(NSString *)path
{
        ASSIGN (RpmPath, path);
	
	        if ([self superview]) {
		                [inspector contentsReadyAt: RpmPath];
				        }

		[editButt setEnabled: YES];	
		[[self window] makeFirstResponder: editButt];

}

- (void)deactivate
{
  [self removeFromSuperview];
}

- (void)displayLastPath:(BOOL)forced
{
	if (RpmPath) {
		if (forced) {
			[self displayPath: RpmPath];
		} else {
			[inspector contentsReadyAt: RpmPath];
		}
	}
}


- (void)displayData:(NSData *)data 
             ofType:(NSString *)type;

{
}

- (NSString *)currentPath
{
	return RpmPath;
}


- (void)stopTasks
{
}

- (BOOL)canDisplayPath:(NSString *)path
{
  // TODO : clean it !!!!!!!!!
  NSTask *task;
  NSFileHandle *stdOutFileHandle,*stdErrFileHande;
  NSPipe *outPipe,*errPipe;
  NSData  *aData,*bData;
  NSString *aString,*bString;
  NSMutableArray *arguments;
  NSArray *args;

        NSDictionary *attributes;
	NSString *defApp, *fileType, *extension;
	NSArray *types;

	attributes = [[NSFileManager defaultManager] fileAttributesAtPath: path
												 traverseLink: YES];
	if ([attributes objectForKey: NSFileType] == NSFileTypeDirectory) {
		return NO;
	}		
			
	[workspace getInfoForFile: path application: &defApp type: &fileType];
	
	if(([fileType isEqual: NSPlainFileType] == NO)
	   && ([fileType isEqual: NSShellCommandFileType] == NO)) {
		return NO;
	}

	extension = [path pathExtension];
	types = [NSArray arrayWithObjects: @"rpm", nil];

        if ([types containsObject: [extension lowercaseString]]) {
  arguments = [[NSMutableArray alloc] init];
  [arguments addObject:@"-qp"];
  [arguments addObject:@"--qf=\"%{NAME}\n%{VERSION}\n%{PACKAGER}\n%{URL}\n%{SIZE}\n%{SUMMARY}\n\""];
  [arguments addObject:path];
  args = [[NSArray alloc] initWithArray: arguments];

  //Define the Pipe
  outPipe = [NSPipe pipe];
  errPipe = [NSPipe pipe];
  stdOutFileHandle = [outPipe fileHandleForReading];
  stdErrFileHande = [errPipe fileHandleForReading];

  task = [[NSTask alloc] init];
  [task setStandardOutput: outPipe];
  [task setStandardError: errPipe];
  [task setLaunchPath: RpmExecPath];      
  [task setArguments: args];
  [task launch];


  //TODO stdErr
  bData = [stdErrFileHande readDataToEndOfFile];
  aData = [stdOutFileHandle readDataToEndOfFile];

  aString = [[NSString alloc] initWithData : aData 
			      encoding     : NSISOLatin1StringEncoding];

  bString = [[NSString alloc] initWithData : bData 
			      encoding     : NSISOLatin1StringEncoding];
  if ([bString length] != 0) 
    {
      NSLog(@"Not Valid ERROR");
      [self _displayError :_(@"The file format is not Valid")];
      return;
    }
  else
    {
      rpmFilesArray = [[NSMutableArray array] retain];
      [rpmFilesArray setArray: [aString componentsSeparatedByString:@"\n"]];
      [rpmFilesArray removeLastObject];
      [self _displayInfo];
    }
    }
}

//}

- (int)index
{
  return index;
}
 
//-(void) setIndex:(int) idx
//{
//  index = idx;
//}

- (void)setBundlePath:(NSString *)path
{
  ASSIGN (bundlePath, path);
}

- (NSString *)bundlePath
{
  return bundlePath;
}

- (NSArray *)pakagesExtensions
{
  return nil;
}

- (BOOL)canDisplayDataOfType:(NSString *)type;

{
    return NO;
}

- (NSString *)winname
{
  return NSLocalizedString(@"Rpm Inspector", @"");
}

-(void) _displayInfo
{

//  [resultPackageName setStringValue:[rpmFilesArray objectAtIndex:0]];
  [resultPackageName setStringValue:[NSString stringWithFormat:@"%@%s", [rpmFilesArray objectAtIndex:0], "\""]];
  [resultPackageVersion setStringValue:[rpmFilesArray objectAtIndex:1]];
  [resultPackageMaintainer setStringValue:[rpmFilesArray objectAtIndex:2]];
  [resultPackageUrl setStringValue:[rpmFilesArray objectAtIndex:3]];
  [resultPackageSize setStringValue:[rpmFilesArray objectAtIndex:4]];
  [resultPackageDescription setString:[rpmFilesArray objectAtIndex:5]];
  
  if (  [errorLabel superview] )
    { 
      [errorLabel removeFromSuperview];
    }

}
-(void) _displayError: (NSString *) error
{
  if ( ! [errorLabel superview] )
    {
      [self addSubview: errorLabel];
    }
  [errorLabel setStringValue: error];
  [buttOk setEnabled: NO];
  [self display];
}  


- (NSString *)description
{
	return NSLocalizedString(@"This Inspector Displays info of RPM files", @"");	
}

@end
