//
//  KMPDFSignatureTextView.m
//  PDF Reader
//
//  Created by 丁林圭 on 2018/6/8.
//  Copyright © 2018年 Kdan Mobile. All rights reserved.
//

#import "KMPDFSignatureTextView.h"
#import "NSImage+CustomImage.h"

#define kKMSignayureTextMaxFontSize 28.0
#define kKMSignayureTextMaxWidth 300
#define kKMSignayureTextEdgeOffset 5

#pragma mark KMVerticallyCenteredSecureTextFieldCell

@interface KMVerticallyCenteredSecureTextFieldCell : NSTextFieldCell
@end
@implementation KMVerticallyCenteredSecureTextFieldCell

- (NSRect)adjustedFrameToVerticallyCenterText:(NSRect)frame
{
//    NSInteger offset = floor((NSHeight(frame)/2 - ([[self font] ascender] + [[self font] descender])));
    NSInteger offset = floor((NSHeight(frame)/2 - ([[self font] ascender])));
    return NSInsetRect(frame, 0.0, offset);
}
- (void)editWithFrame:(NSRect)aRect inView:(NSView *)controlView editor:(NSText *)editor delegate:(id)delegate event:(NSEvent *)event
{
    [super editWithFrame:[self adjustedFrameToVerticallyCenterText:aRect] inView:controlView editor:editor delegate:delegate event:event];
}
- (void)selectWithFrame:(NSRect)aRect inView:(NSView *)controlView editor:(NSText *)editor delegate:(id)delegate start:(NSInteger)start length:(NSInteger)length
{
    [super selectWithFrame:[self adjustedFrameToVerticallyCenterText:aRect] inView:controlView editor:editor delegate:delegate start:start length:length];
}
- (void)drawInteriorWithFrame:(NSRect)frame inView:(NSView *)view
{
    [super drawInteriorWithFrame:
    [self adjustedFrameToVerticallyCenterText:frame] inView:view];
}

@end

@interface KMSignayureTextField : NSTextField

@property (nonatomic, retain) NSColor *originalTextColor;
@end


@implementation KMSignayureTextField

- (void)addSubview:(NSView *)view {
    [super addSubview:view];
    NSView * view1  =  view.subviews.firstObject;
    if ([view1 isKindOfClass:[NSTextView class]]) {
        NSTextView * textview = (NSTextView *)view1;
        [textview setInsertionPointColor:[NSColor colorWithRed:102.0/255.0 green:102.0/255.0 blue:102.0/255.0 alpha:1.0]];
    }
}

@end


@interface KMPDFSignatureTextView()

@property (nonatomic) IBOutlet KMSignayureTextField *nameTextFiled;

@property (assign) IBOutlet NSLayoutConstraint *labelWidthLayoutConstraint;

@property (nonatomic) IBOutlet NSBox *verticalLineBox;

@end

@implementation KMPDFSignatureTextView

- (id)initWithFrame:(NSRect)frameRect
{
    if (self = [super initWithFrame:frameRect])
    {
        self.keyboardColor = [NSColor colorWithDeviceRed:0 green:0 blue:0 alpha:1];
        
        self.wantsLayer = YES;
        self.layer.borderWidth = 1.0;
        self.layer.borderColor =[NSColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.05].CGColor;
        self.layer.backgroundColor = [NSColor colorWithRed:1 green:1 blue:1 alpha:0.9].CGColor;

    }
    return self;
}

-(void)awakeFromNib
{
    [super awakeFromNib];
    
//    NSMutableParagraphStyle *paragraphStyle = [[[NSMutableParagraphStyle alloc] init] autorelease];
//    paragraphStyle.alignment = NSTextAlignmentCenter;
//
//    NSAttributedString *att = [[[NSAttributedString alloc] initWithString:NSLocalizedString(@"Sign Here",nil) attributes:@{NSForegroundColorAttributeName:[KMAppearance KMColor_Layout_H2],NSFontAttributeName:[NSFont systemFontOfSize:14.0],                                NSParagraphStyleAttributeName:paragraphStyle}] autorelease];
//
//    [self.nameTextFiled.cell setPlaceholderAttributedString:att];
    self.nameTextFiled.placeholderString = NSLocalizedString(@"Sign Here",nil);
    self.nameTextFiled.font = [NSFont systemFontOfSize:14.0];
    [self.verticalLineBox setFillColor:[NSColor blackColor]];
}

#pragma mark - Public Method
- (void)clearImage
{
    self.nameTextFiled.stringValue = @"";
    self.nameTextFiled.font = [NSFont systemFontOfSize:14.0];
    if (self.changeSignatureTextCallback) {
        self.changeSignatureTextCallback(NO);
    }
    
}

- (NSImage *)signatureImage
{
    CGRect rect = CGRectZero;
    NSString * string = self.nameTextFiled.stringValue?:@"";
    CGSize size = [self sizeOfString:string witFontSize:self.nameTextFiled.font];
    
    if (size.width == 0) {
        return nil;
    } else {
        rect = CGRectMake(kKMSignayureTextEdgeOffset,kKMSignayureTextEdgeOffset, size.width, size.height);
    }

    NSImage *image = [[NSImage alloc] initWithSize:CGSizeMake(size.width + kKMSignayureTextEdgeOffset* 2, size.height + kKMSignayureTextEdgeOffset* 2)];
    [image lockFocus];
    
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
    [dictionary setObject:self.nameTextFiled.font forKey:NSFontAttributeName];
    [dictionary setObject:self.keyboardColor forKey:NSForegroundColorAttributeName];
    [string drawInRect:rect withAttributes:dictionary];
    
    [image unlockFocus];
    return image;
}

- (void)setKeyboardColor:(NSColor *)keyboardColor
{
    _keyboardColor = keyboardColor;
    self.nameTextFiled.textColor = keyboardColor;
}

- (void)setFontName:(NSString *)fontName
{
    _fontName = fontName;
    CGFloat fontSize = 14.0;
    if (self.nameTextFiled.stringValue.length > 0) {
        fontSize = kKMSignayureTextMaxFontSize;
    }
    NSFont * maxFont = [NSFont fontWithName:_fontName size:fontSize];
    CGSize size = [self sizeOfString:self.nameTextFiled.stringValue witFontSize:maxFont];
    
    CGFloat width = size.width + kKMSignayureTextEdgeOffset * 2;
    CGFloat scanel = 1.0;
    
    scanel = MIN(kKMSignayureTextMaxWidth/width, 60.0/(size.height + 2));
    
    NSFont* font = [NSFont fontWithName:_fontName size:fontSize];
    self.nameTextFiled.font = font;
}

#pragma mark - NSTextFieldDelegate
- (void)controlTextDidChange:(NSNotification *)obj
{
    NSTextField *textField = (NSTextField*)[obj object];
    if (textField == self.nameTextFiled) {
        NSString *string = textField.stringValue.length > 0 ? textField.stringValue : nil;
        CGFloat fontSize = 14.0;
        if (string) {
            fontSize = kKMSignayureTextMaxFontSize;
        }
        NSFont * maxFont = [NSFont fontWithName:_fontName size:fontSize];
        CGSize size = [self sizeOfString:string witFontSize:maxFont];
        
        CGFloat width = size.width + kKMSignayureTextEdgeOffset * 2;
        CGFloat scanel = 1.0;
        
        scanel = MIN((self.bounds.size.width - 30)/width, 60.0/(size.height + 2));
        
        if (width >= 100) {
            self.labelWidthLayoutConstraint.constant = width;
        }
        NSFont* font = [NSFont fontWithName:_fontName size:fontSize];
        self.nameTextFiled.font = font;
        
        BOOL isTure = textField.stringValue.length > 0 ? YES : NO;
        if (self.changeSignatureTextCallback) {
            self.changeSignatureTextCallback(isTure);
        }
        if([self.delegate respondsToSelector:@selector(changeSignatureText:)]) {
            [self.delegate changeSignatureText:isTure];
        }
    }
}

- (NSSize)sizeOfString:(NSString *)string witFontSize:(NSFont *)font
{
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
    [dictionary setObject:font forKey:NSFontAttributeName];
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    [style setAlignment:NSCenterTextAlignment];
    [dictionary setObject:style forKey:NSParagraphStyleAttributeName];
    
    CGSize size = [string boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT)
                                       options:NSStringDrawingUsesLineFragmentOrigin
                                    attributes:dictionary].size;
    
    return size;
}

@end