/*
SRURLComboBoxCell.m

Author: Makoto Kinoshita

Copyright 2004 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 "SRMainWindowController.h"
#import "SRBookmark.h"
#import "SRBookmarkStorage.h"

#import "SRURLAutoComplete.h"
#import "SRURLComboBox.h"
#import "SRURLComboBoxCell.h"

#import "AppKitEx.h"
#import "WebKitEx.h"

static int  _SRIconMargin = 2;

@implementation SRURLComboBoxCell

- (void)dealloc
{
    [_image release];
    _image = nil;
    [super dealloc];
}

- (id)copyWithZone:(NSZone*)zone
{
    SRURLComboBoxCell*    cell;
    cell = (SRURLComboBoxCell *)[super copyWithZone:zone];
    cell->_image = [_image retain];
    return cell;
}

- (void)setImage:(NSImage*)image {
    if (_image != image) {
        [_image release];
        _image = [image retain];
        
        [[self controlView] setNeedsDisplay:YES];
    }
}

- (NSImage *)image {
    return _image;
}

- (NSRect)imageFrameForCellFrame:(NSRect)cellFrame
{
    if (_image) {
        NSRect imageFrame;
        imageFrame.size = [_image size];
        imageFrame.origin = cellFrame.origin;
        imageFrame.origin.x += 3;
        imageFrame.origin.y += ceil((cellFrame.size.height - imageFrame.size.height) / 2);
        return imageFrame;
    }
    else {
        return NSZeroRect;
    }
}

- (void)selectWithFrame:(NSRect)rect 
        inView:(NSView*)controlView 
        editor:(NSText*)textObj 
        delegate:(id)object 
        start:(int)selStart 
        length:(int)selLength
{
    NSRect  textFrame, imageFrame, buttonFrame;
    NSDivideRect(rect, &imageFrame, &textFrame, _SRIconMargin + [_image size].width, NSMinXEdge);
    buttonFrame = [(SRURLComboBox*)controlView buttonFrame];
    textFrame.size.width -= buttonFrame.size.width + 2;
    [super selectWithFrame:textFrame 
            inView:controlView 
            editor:textObj 
            delegate:object 
            start:selStart 
            length:selLength];
}

- (void)editWithFrame:(NSRect)rect 
        inView:(NSView*)controlView 
        editor:(NSText*)textObj 
        delegate:(id)object 
        event:(NSEvent*)event 
{
    NSRect  textFrame, imageFrame, buttonFrame;
    NSDivideRect(rect, &imageFrame, &textFrame, _SRIconMargin + [_image size].width, NSMinXEdge);
    buttonFrame = [(SRURLComboBox*)controlView buttonFrame];
    textFrame.size.width -= buttonFrame.size.width + 2;
    [super editWithFrame:textFrame 
            inView:controlView 
            editor:textObj 
            delegate:object 
            event:event];
}

- (void)drawInteriorWithFrame:(NSRect)cellFrame 
        inView:(NSView*)controlView
{
    if (_image != nil) {
        NSSize	imageSize;
        NSRect	imageFrame;
        
        imageSize = [_image size];
        NSDivideRect(cellFrame, &imageFrame, &cellFrame, _SRIconMargin + imageSize.width, NSMinXEdge);
        imageFrame.origin.x += 3;
        imageFrame.size = imageSize;
        imageFrame.origin.y += ceil((cellFrame.size.height - imageFrame.size.height) / 2);
        if ([self drawsBackground]) {
            [[self backgroundColor] set];
            NSRectFill(imageFrame);
        }
        
        imageFrame.origin.y = cellFrame.origin.y;
        if ([controlView isFlipped]) {
            imageFrame.origin.y += ceil((cellFrame.size.height + imageFrame.size.height) / 2);
        }
        else {
            imageFrame.origin.y += ceil((cellFrame.size.height - imageFrame.size.height) / 2);
        }
        
        [_image compositeToPoint:imageFrame.origin operation:NSCompositeSourceOver];
    }
    [super drawInteriorWithFrame:cellFrame inView:controlView];
}

- (NSSize)cellSize
{
    NSSize cellSize = [super cellSize];
    cellSize.width += (_image ? [_image size].width : 0) + _SRIconMargin;
    return cellSize;
}

- (void)_drawFocusRingWithFrame:(NSRect)rect
{
    if (_image) {
        rect.origin.x -= [_image size].width + _SRIconMargin;
        rect.size.width += [_image size].width + _SRIconMargin;
    }
    
    NSRect  buttonFrame;
    buttonFrame = [(SRURLComboBox*)[self controlView] buttonFrame];
    if (buttonFrame.size.width > 0) {
        rect.size.width += buttonFrame.size.width + 2;
    }
    
    rect = NSInsetRect(rect, 1.0, 1.0);
    [super _drawFocusRingWithFrame:rect];
}

- (BOOL)shouldImageTrackMouse:(NSEvent*)event 
        inRect:(NSRect)cellFrame 
        ofView:(NSView*)controlView 
{
    // Check mouse is in image or not
    NSRect  imageFrame;
    NSPoint point;
    imageFrame = [self imageFrameForCellFrame:cellFrame];
    point = [controlView convertPoint:[event locationInWindow] fromView:nil];
    
    if (NSPointInRect(point, imageFrame)) {
		return YES;
	}
	return NO;
}

- (BOOL)imageTrackMouse:(NSEvent*)event 
        inRect:(NSRect)cellFrame 
        ofView:(NSView*)controlView 
{
    // Check mouse is in image or not
    NSRect  imageFrame;
    NSPoint point;
    imageFrame = [self imageFrameForCellFrame:cellFrame];
    point = [controlView convertPoint:[event locationInWindow] fromView:nil];
    
    if (NSPointInRect(point, imageFrame)) {
        //
        // Start dragging
        //
        
        // Get URL string and title from web data source
        WebDataSource*  dataSource;
        NSString*       pageURLString;
        NSString*       title;
        dataSource = [[[[[controlView window] windowController] selectedWebView] mainFrame] dataSource];
        pageURLString = [[[dataSource request] URL] _web_userVisibleString];
        title = [dataSource pageTitle];
        
        // Get URL string from itself
        NSString*   URLString;
        URLString = [self stringValue];
        if (!URLString) {
            // User URL string from web data source
            URLString = pageURLString;
        }
        else if (![URLString isEqualToString:pageURLString]) {
            // Use URL string as title
            title = URLString;
        }
        
        if (!URLString || [URLString length] == 0) {
            return NO;
        }
        
        // Get attributed sring and its size
        NSAttributedString* attrString;
        NSSize              stringSize;
        attrString = [self attributedStringValue];
		//if string is too long causes "Can't cache image" error. so truncate
		if([attrString length]>300){
			attrString = [attrString attributedSubstringFromRange:NSMakeRange(0,300)];
		}
        stringSize = [attrString size];
		if(stringSize.width>1000){
			stringSize.width=1000;
		}
        
        // Create image
        NSSize      imageSize;
        NSImage*    dragImage;
        imageSize = stringSize;
        imageSize.width += [_image size].width + _SRIconMargin;
        dragImage = [[NSImage alloc] initWithSize:imageSize];
        [dragImage autorelease];
        
        // Draw image
        NSMutableAttributedString*  coloredAttrString;
        float                       alpha = 0.7;
        
        coloredAttrString = [[NSMutableAttributedString alloc] 
                initWithAttributedString:attrString];
        [coloredAttrString autorelease];
        [coloredAttrString addAttribute:NSForegroundColorAttributeName 
                value:[NSColor colorWithCalibratedWhite:0.0 alpha:alpha] 
                range:NSMakeRange(0, [attrString length])];
        
        [NSGraphicsContext saveGraphicsState];
        [dragImage lockFocus];
        [_image dissolveToPoint:NSZeroPoint fraction:alpha];
        [coloredAttrString drawAtPoint:NSMakePoint([_image size].width + _SRIconMargin, 0)];
        [dragImage unlockFocus];
        [NSGraphicsContext restoreGraphicsState];
        
        // Create bookmark data
        SRBookmark* bookmark;
        bookmark = [SRBookmark bookmarkWithTitle:title 
                URLString:URLString 
                originalBrowser:SRBrowserShiira];
        
        // Write bookmark to pasteboard
        NSPasteboard*   pboard;
        pboard = [NSPasteboard pasteboardWithName:NSDragPboard];
        SRWriteBookmarksToPasteboard([NSArray arrayWithObject:bookmark], pboard);
        
        // Start dragging
        NSPoint startAt;
        startAt = imageFrame.origin;
        if ([controlView isFlipped]) {
            startAt.y = cellFrame.size.height - startAt.y;
        }
        
        [controlView dragImage:dragImage 
                at:startAt 
                offset:NSZeroSize 
                event:event 
                pasteboard:pboard 
                source:self 
                slideBack:YES];
        
        return YES;
    }
    
    return NO;
}

- (void)resetCursorRect:(NSRect)cellFrame 
        inView:(NSView*)controlView
{
    NSRect  textFrame;
    NSRect  imageFrame;
    NSDivideRect(cellFrame, &imageFrame, &textFrame, _SRIconMargin + [_image size].width, NSMinXEdge);
    [super resetCursorRect:textFrame inView:controlView];
}

@end
