//
//  KMSignatureWindowController.m
//  PDF Reader Premium
//
//  Created by wangshuai on 14/12/3.
//  Copyright (c) 2014年 zhangjie. All rights reserved.
//

#import "KMSignatureWindowController.h"
#import "NSImage+PDFListView.h"
#import "KMPurchaseCompareWindowController.h"
#import "NSMenu_SKExtensions.h"

#import <PDF_Reader_Pro-Swift.h>

static NSMutableArray * recentlyFonts;

#pragma mark KMSignatureColorButton
@interface KMSignatureColorButton : NSButton

@property (nonatomic, retain) NSColor *circleColor;
@property (nonatomic, retain) NSImage *drawImage;

@end

@implementation KMSignatureColorButton

- (void)dealloc {
   
}

//- (void)setCircleColor:(NSColor *)circleColor {
//    if (_circleColor != circleColor) {
//        _circleColor  = circleColor;
//    }
//    [self setNeedsDisplay:YES];
//}

- (id)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];
    if (self) {
        self.wantsLayer = YES;
        self.layer.cornerRadius = 12;
        self.layer.masksToBounds = YES;
        self.layer.borderWidth = 1.5;
    }
    return self;
}

- (void)drawRect:(NSRect)rect {
    [super drawRect:rect];
    if (_circleColor) {
        NSBezierPath *path3 = [NSBezierPath bezierPathWithOvalInRect:NSMakeRect(3, 3, rect.size.width - 6,  rect.size.height - 6)];
        [self.circleColor set];
        [path3 fill];
    } else if (self.drawImage) {
        [self.drawImage drawInRect:CGRectMake(3,3,rect.size.width -6,rect.size.height - 6)
                         fromRect:NSZeroRect
                         operation:NSCompositingOperationSourceOver
                          fraction:1.0];
    }
}

@end


#pragma mark KMSignatureButton
@interface KMSignatureButton : NSButton

@end

@implementation KMSignatureButton

- (NSMenu *)menuForEvent:(NSEvent *)theEvent {
    NSMenu *menu = [[NSMenu alloc] initWithTitle:@""];
    NSMenuItem *item = [menu addItemWithTitle:NSLocalizedString(@"Delete", nil) action:@selector(delete) keyEquivalent:@""];
    item.target = self;
    
    item = [menu addItemWithTitle:NSLocalizedString(@"Export", @"Menu item title") action:nil keyEquivalent:@""];
    
    NSMenu * tSubMenu = [NSMenu menu];
    
    NSMenuItem *tMenuItem = [tSubMenu insertItemWithTitle:NSLocalizedString(@"PNG", @"Menu item title") action:@selector(export:) target:self atIndex:0];
    tMenuItem.tag = 0;
    
    tMenuItem = [tSubMenu insertItemWithTitle:NSLocalizedString(@"JPG", @"Menu item title") action:@selector(export:) target:self atIndex:1];
    tMenuItem.tag = 1;

    tMenuItem = [tSubMenu insertItemWithTitle:NSLocalizedString(@"PDF", @"Menu item title") action:@selector(export:) target:self atIndex:2];
    tMenuItem.tag = 2;
    
    item.submenu = tSubMenu;
    
    return menu;
}

- (void)delete {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"kKMSignatureDeleteNotification" object:[NSNumber numberWithInteger:self.tag]];
}

- (void)export:(NSMenuItem *)sender {
    NSInteger index = self.tag;
    NSInteger type = sender.tag;
    
    KMSignatureManager *signatureManager = [[KMSignatureManager alloc] init];
    [signatureManager loadAllSignatureList];
    KMSignature *signature = signatureManager.signatureList[index];
    NSImage *image = signature.pathsImage;
    
    if (type == 0) {
        NSData *data = image.TIFFRepresentation;
        NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:data];
        [imageRep setSize:image.size];
        NSData *imageData = [imageRep representationUsingType:NSBitmapImageFileTypePNG properties:@{}];
        
        NSSavePanel *savePanel = [NSSavePanel savePanel];
        savePanel.allowedFileTypes = @[@"png"];
        [savePanel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) {
            if (result) {
                if ([imageData writeToURL:savePanel.URL atomically:YES]) {
                    [[NSWorkspace sharedWorkspace] selectFile:savePanel.URL.path
                                     inFileViewerRootedAtPath:@""];
                }
            }
        }];
    } else if (type == 1) {
        NSData *data = image.TIFFRepresentation;
        NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:data];
        [imageRep setSize:image.size];
        NSData *imageData = [imageRep representationUsingType:NSBitmapImageFileTypeJPEG properties:@{}];
        
        NSSavePanel *savePanel = [NSSavePanel savePanel];
        savePanel.allowedFileTypes = @[@"jpg"];
        [savePanel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) {
            if (result) {
                if ([imageData writeToURL:savePanel.URL atomically:YES]) {
                    [[NSWorkspace sharedWorkspace] selectFile:savePanel.URL.path
                                     inFileViewerRootedAtPath:@""];
                }
            }
        }];
    } else {
        PDFDocument *pdf = [[PDFDocument alloc] init];
        PDFPage *page = [[PDFPage alloc] initWithImage:image];
        [pdf insertPage:page atIndex:pdf.pageCount];
        
        NSSavePanel *savePanel = [NSSavePanel savePanel];
        savePanel.allowedFileTypes = @[@"pdf"];
        [savePanel beginSheetModalForWindow:[NSApp mainWindow] completionHandler:^(NSInteger result) {
            if (result) {
                if ([pdf writeToURL:savePanel.URL]) {
                    [[NSWorkspace sharedWorkspace] selectFile:savePanel.URL.path
                                     inFileViewerRootedAtPath:@""];
                }
            }
        }];
    }
}

@end

#pragma mark KMSignatureWindowController
@interface KMSignatureWindowController () <NSTabViewDelegate,KMDrawViewDelegate,KMChangeSignatureTextDelegate>

@property (nonatomic) IBOutlet NSTabView   *creatTabview;

@property (nonatomic) IBOutlet NSButton    *cancelBtton;
@property (nonatomic) IBOutlet NSButton    *applyButton;
@property (nonatomic) IBOutlet NSButton    *clearButton;

@property (nonatomic) IBOutlet KMPDFSignatureTextView *keyboardView;
@property (nonatomic) IBOutlet NSPopUpButton *fontBox;
@property (nonatomic) IBOutlet KMSignatureColorButton    *textBlackColorButton;
@property (nonatomic) IBOutlet KMSignatureColorButton    *textBlueColorButton;
@property (nonatomic) IBOutlet KMSignatureColorButton    *textPurpleColorButton;
@property (nonatomic) IBOutlet KMSignatureColorButton    *textGreenColorButton;
@property (nonatomic) IBOutlet KMSignatureColorButton    *textOrangeColorButton;
@property (nonatomic) IBOutlet KMSignatureColorButton    *textRedColorButton;
@property (nonatomic,assign) IBOutlet KMSignatureColorButton *textColorButton;

@property (nonatomic) IBOutlet KMDrawView  *drawView;
@property (nonatomic) IBOutlet NSButton    *trackpadButton;
@property (assign) IBOutlet NSSlider *slider;

@property (nonatomic) IBOutlet KMSignatureColorButton    *mouseBlackColorButton;
@property (nonatomic) IBOutlet KMSignatureColorButton    *mouseBlueColorButton;
@property (nonatomic) IBOutlet KMSignatureColorButton    *mousePurpleColorButton;
@property (nonatomic) IBOutlet KMSignatureColorButton    *mouseGreenColorButton;
@property (nonatomic) IBOutlet KMSignatureColorButton    *mouseOrangeColorButton;
@property (nonatomic) IBOutlet KMSignatureColorButton    *mouseRedColorButton;
@property (nonatomic, assign) IBOutlet KMSignatureColorButton *mouseColorButton;

@property (nonatomic) IBOutlet KMPDFSignatureImageView *pictureBackView;

@property (nonatomic) IBOutlet NSTextField *trackpadLabel;
@property (assign) IBOutlet NSTextField *widthSizeTextField;

@property (nonatomic, retain) KMSignature   *selectedSignature;
@property (nonatomic, retain) NSMenuItem *selectItem;
@property (nonatomic, assign) KMPDFSignatureType   type;

@end

@implementation KMSignatureWindowController

- (id)init {
    if (self = [super initWithWindowNibName:@"KMSignatureWindowController"]) {

    }
    return self;
}

- (void)dealloc {
    _creatTabview.delegate = nil;
    _drawView.delegate = nil;
    _keyboardView.delegate = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [NSDistributedNotificationCenter.defaultCenter removeObserver:self];
    [[NSColorPanel sharedColorPanel] setTarget:nil];
    [[NSColorPanel sharedColorPanel] setAction:nil];
}

#pragma mark - View Methods

- (void)windowDidLoad {
    [super windowDidLoad];
    
    self.type = KMPDFSignatureTypeText;
    
    self.textBlackColorButton.circleColor = self.mouseBlackColorButton.circleColor = [NSColor blackColor];
    
    self.textRedColorButton.circleColor =
    self.mouseRedColorButton.circleColor = [NSColor colorWithRed:221.0f/255.0f green:2.0f/255.0f blue:2.0f/255.0f alpha:1.0f];
    
    self.textBlueColorButton.circleColor =
    self.mouseBlueColorButton.circleColor  = [NSColor colorWithRed:0.0 green:52.0/255.0 blue:146.0/255.0 alpha:1.0];
    
    self.textGreenColorButton.circleColor =
    self.mouseGreenColorButton.circleColor = [NSColor colorWithRed:39.0f/255.0f green:190.0f/255.0f blue:253.0f/255.0f alpha:1.0f];
    
    self.textOrangeColorButton.circleColor =
    self.mouseOrangeColorButton.circleColor = [NSColor colorWithRed:253.0f/255.0f green:126.0f/255.0f blue:21.0f/255.0f alpha:1.0f];
    
    self.textPurpleColorButton.circleColor =
    self.mousePurpleColorButton.circleColor = [NSColor colorWithRed:100.0/255.0 green:13.0/255.0 blue:168.0/255.0 alpha:1.0];
    
    self.textColorButton.drawImage = self.mouseColorButton.drawImage = [NSImage imageNamed:@"view_color"];
    
    self.widthSizeTextField.backgroundColor = [KMAppearance KMColor_Layout_L1];
    self.widthSizeTextField.wantsLayer = YES;
    self.widthSizeTextField.layer.borderWidth = 0;
    
    [self localizedString];
    
    [self.cancelBtton setTarget:self];
    [self.cancelBtton setAction:@selector(dismissSheet:)];
    
    [self.clearButton setTarget:self];
    [self.clearButton setAction:@selector(clearButton_Click:)];
    
    self.applyButton.enabled = NO;
    [self.applyButton setTarget:self];
    [self.applyButton setAction:@selector(applyButton_Click:)];
    
    self.keyboardView.wantsLayer = YES;
    
    self.drawView.delegate = self;
    self.drawView.wantsLayer = YES;
    self.drawView.layer.masksToBounds = YES;
    
    self.pictureBackView.wantsLayer = YES;
    
    [self.creatTabview selectFirstTabViewItem:nil];
    
    [self.trackpadLabel setHidden:YES];
    
    _slider.floatValue = self.drawView.strokeRadius;
    _widthSizeTextField.stringValue = [NSString stringWithFormat:@"%.1f",self.drawView.strokeRadius];
    
    __block typeof(self) blockSelf = self;
    self.keyboardView.delegate = self;
    self.drawView.changeDrawCallback = ^(BOOL isTure) {
        if (isTure) {
            blockSelf.applyButton.enabled = YES;
        } else {
            blockSelf.applyButton.enabled = NO;
        }
    };
    self.pictureBackView.changeSignatureImageCallback = ^(BOOL isTure) {
        if (isTure) {
            blockSelf.applyButton.enabled = YES;
        } else {
            blockSelf.applyButton.enabled = NO;
        }
    };
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(widthSizeTextFieldNotification:) name:NSControlTextDidChangeNotification object:_widthSizeTextField];
    [NSDistributedNotificationCenter.defaultCenter addObserver:self selector:@selector(themeChanged:) name:@"AppleInterfaceThemeChangedNotification" object: nil];
    
    [self updateViewColor];
}

#pragma mark - Private Methods

- (void)localizedString {
    self.creatTabview.delegate = self;
    
    [self.trackpadButton setTitle:NSLocalizedString(@"Trackpad", nil)];
    [self.cancelBtton setTitle:NSLocalizedString(@"Cancel",nil)];
    [self.applyButton setTitle:NSLocalizedString(@"Save", nil)];
    [self.clearButton setTitle:NSLocalizedString(@"Clear", nil)];
    [self.trackpadLabel setStringValue:NSLocalizedString(@"Press \"esc\" to disable the Trackpad.", nil)];
    
    NSArray *seletorFonts = @[@"Mistral", @"Bradley Hand", @"Brush Script MT", @"SignPainter", @"Edwardian Script ITC", @"American Typewriter",@"Baoli SC",@"Snell Roundhand", @"Apple Chancery", @"Monotype Corsiva"];
    
    NSArray *fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
    for (NSString *fontName in fonts) {
        NSDictionary *attrited = @{NSFontAttributeName:[NSFont fontWithName:fontName size:12.0]};
        NSAttributedString *string = [[NSAttributedString alloc] initWithString:fontName attributes:attrited];
        NSMenuItem *item = [[NSMenuItem alloc] init];
        item.attributedTitle = string;
        [self.fontBox.menu addItem:item];
    }
    
    NSString * fontName = nil;
    
    if (!recentlyFonts) {
        recentlyFonts = [[NSMutableArray alloc] init];
    }
    if (recentlyFonts.count < 1) {
        for (NSString *name in seletorFonts) {
            if ([fonts containsObject:name]) {
                fontName = name;
                break;
            }
        }
        if (fontName) {
            [recentlyFonts addObject:fontName];
        }
    } else {
        fontName = recentlyFonts.firstObject;
    }
    
    if ([fonts containsObject:fontName]) {
        self.keyboardView.fontName = fontName;
        [self.fontBox setTitle:fontName];
    } else {
        self.keyboardView.fontName = fonts.firstObject;
        [self.fontBox setTitle:fonts.firstObject];
    }
    
    for (NSUInteger i = 0; i<recentlyFonts.count; i++) {
        NSString *fontName  = recentlyFonts[i];
        NSDictionary *attrited = @{NSFontAttributeName:[NSFont fontWithName:fontName size:12.0]};
        NSAttributedString *string = [[NSAttributedString alloc] initWithString:fontName attributes:attrited];
        NSMenuItem *item = [[NSMenuItem alloc] init];
        item.attributedTitle = string;
        [self.fontBox.menu insertItem:item atIndex:1 + i];
    }
    NSMenuItem *sep = [NSMenuItem separatorItem];
    [self.fontBox.menu  insertItem:sep atIndex:(recentlyFonts.count)+1];
    
    self.selectItem=  [self.fontBox.menu itemAtIndex:1];
    self.selectItem.state = NSControlStateValueOn;
        
    [[self.creatTabview tabViewItemAtIndex:0] setLabel:NSLocalizedString(@"Keyboard", nil)];
    [[self.creatTabview tabViewItemAtIndex:1] setLabel:NSLocalizedString(@"Trackpad", nil)];
    [[self.creatTabview tabViewItemAtIndex:2] setLabel:NSLocalizedString(@"Image", nil)];
    
    [self colorInkButtonAction:self.mouseBlackColorButton];
    [self colorTextButtonAction:self.textBlackColorButton];
}

- (void)updateViewColor {
    if ([KMAppearance isDarkMode]) {
        self.keyboardView.layer.backgroundColor = [NSColor colorWithRed:57/255. green:60/255. blue:62/255. alpha:1.].CGColor;
        self.drawView.layer.backgroundColor = [NSColor colorWithRed:57/255. green:60/255. blue:62/255. alpha:1.].CGColor;
        self.pictureBackView.layer.backgroundColor = [NSColor colorWithRed:57/255. green:60/255. blue:62/255. alpha:1.].CGColor;
        
    } else {
        self.keyboardView.layer.backgroundColor = [NSColor whiteColor].CGColor;
        self.drawView.layer.backgroundColor = [NSColor whiteColor].CGColor;
        self.pictureBackView.layer.backgroundColor = [NSColor whiteColor].CGColor;
        
    }
}

#pragma mark - Button Mehtods

- (void)clearButton_Click:(id)sender {
    if (KMPDFSignatureTypeImage == self.type) {
        [self.pictureBackView clearImage];
    } else if (KMPDFSignatureTypeInk == self.type) {
        [self.drawView clearImage];
    } else if (KMPDFSignatureTypeText == self.type) {
        [self.keyboardView clearImage];
    }
    
    self.applyButton.enabled = NO;
}

- (NSImage*)changeColor:(NSColor*)color oldImage:(NSImage *)oldImage {

    NSImage *newImage = [oldImage copy];

    [newImage lockFocus];

    [color set];

    NSRect imageRect=NSMakeRect(0, 0, oldImage.size.width, oldImage.size.height);

    NSRectFillUsingOperation(imageRect, NSCompositingOperationSourceAtop);

    [newImage unlockFocus];

    return newImage;
}

- (void)applyButton_Click:(id)sender {
    KMSignature *signature = [[KMSignature alloc] init];

    if (KMPDFSignatureTypeText == self.type) {
        NSImage *image = [self.keyboardView signatureImage];
        
        if (!image) {
            NSAlert *alert = [[NSAlert alloc] init];
            [alert setAlertStyle:NSAlertStyleCritical];
            [alert setMessageText:NSLocalizedString(@"Unable to add new signatures. Please try again.",nil)];
            [alert runModal];
            return;
        }
        
        signature.pathsImage = image;
        signature.signatureType = KMPDFSignatureTypeText;
        KMSignatureManager *signatureManager = [[KMSignatureManager alloc] init];
        [signatureManager loadAllSignatureList];
        [signatureManager addSignature:signature];
        [signatureManager saveSingaturesToFile];
    } else if(KMPDFSignatureTypeImage == self.type) {
        NSImage *image = [self.pictureBackView signatureImage];
        
        if (!image) {
            NSAlert *alert = [[NSAlert alloc] init];
            [alert setAlertStyle:NSAlertStyleCritical];
            [alert setMessageText:NSLocalizedString(@"Unable to add new signatures. Please try again.",nil)];
            [alert runModal];
            return;
        }
        
        signature.pathsImage = image;
        signature.signatureType = KMPDFSignatureTypeImage;

        KMSignatureManager *signatureManager = [[KMSignatureManager alloc] init];
        [signatureManager loadAllSignatureList];
        [signatureManager addSignature:signature];
        [signatureManager saveSingaturesToFile];
    } else {
        NSImage *image = [self.drawView signatureImage];
        
        if (!image) {
            NSAlert *alert = [[NSAlert alloc] init];
            [alert setAlertStyle:NSAlertStyleCritical];
            [alert setMessageText:NSLocalizedString(@"Unable to add new signatures. Please try again.",nil)];
            [alert runModal];
            return;
        }
        
        [signature addPath:self.drawView.drawBezierPath];
        signature.signatureType = KMPDFSignatureTypeInk;
        signature.signatureColor = self.drawView.drawColor;
        signature.pathsImage = image;
        KMSignatureManager *signatureManager = [[KMSignatureManager alloc] init];
        [signatureManager loadAllSignatureList];
        [signatureManager addSignature:signature];
        [signatureManager saveSingaturesToFile];
    }
    self.selectedSignature = signature;
    [self dismissSheet:nil];
}

- (IBAction)trackpadButton_Click:(id)sender {
    if (self.trackpadButton.cell.state) {
        [self.trackpadLabel setHidden:NO];
        self.drawView.isAcceptsTouch = YES;
    } else {
        [self.trackpadLabel setHidden:YES];
        self.drawView.isAcceptsTouch = NO;
    }
}

- (IBAction)boxItemClicked_Font:(id)sender {
    NSString * name = self.fontBox.selectedItem.title;
    self.fontBox.title = name;
    self.keyboardView.fontName = name;

    if ([recentlyFonts containsObject:name]) {
        NSInteger index = [recentlyFonts indexOfObject:name];
        [recentlyFonts removeObject:name];
        [self.fontBox.menu removeItemAtIndex:index +1];
        
    }
    if (recentlyFonts.count >0) {
        [recentlyFonts insertObject:name atIndex:0];
    } else {
        [recentlyFonts addObject:name];
    }

    if (recentlyFonts.count >5) {
        [recentlyFonts removeLastObject];
        [self.fontBox.menu removeItemAtIndex:recentlyFonts.count];
    }

    NSDictionary *attrited = @{NSFontAttributeName:[NSFont fontWithName:name size:12.0]};
    NSAttributedString *string = [[NSAttributedString alloc] initWithString:name attributes:attrited];
    NSMenuItem *item = [[NSMenuItem alloc] init];
    item.attributedTitle = string;
    [self.fontBox.menu  insertItem:item atIndex:1];
    
    self.selectItem.state = NSControlStateValueOff;
    self.selectItem =  [self.fontBox.menu itemAtIndex:1];
    self.selectItem.state = NSControlStateValueOn;
}

- (IBAction)slider_Change:(id)sender {
    self.drawView.strokeRadius = self.slider.floatValue;
    
    _widthSizeTextField.stringValue = [NSString stringWithFormat:@"%.1f",self.slider.floatValue];
}

- (IBAction)colorTextButtonAction:(KMSignatureColorButton *)sender {
    if (sender.tag != 6) {
        self.textBlackColorButton.layer.borderColor =
        self.textRedColorButton.layer.borderColor =
        self.textBlueColorButton.layer.borderColor =
        self.textGreenColorButton.layer.borderColor =
        self.textOrangeColorButton.layer.borderColor =
        self.textPurpleColorButton.layer.borderColor  =
        self.textColorButton.layer.borderColor= [NSColor clearColor].CGColor;
        self.keyboardView.keyboardColor = sender.circleColor;
        sender.layer.borderColor = [KMAppearance KMColor_Interactive_A0].CGColor;
    } else {
        [[NSColorPanel sharedColorPanel] setTarget:self];
        [[NSColorPanel sharedColorPanel] setAction:@selector(keyboardColorPanelColorDidChange:)];
        [[NSColorPanel sharedColorPanel] orderFront:nil];
    }
}

- (IBAction)colorInkButtonAction:(KMSignatureColorButton *)sender {
    if (sender.tag != 6) {
        self.mouseBlackColorButton.layer.borderColor =
        self.mouseRedColorButton.layer.borderColor =
        self.mouseBlueColorButton.layer.borderColor =
        self.mouseGreenColorButton.layer.borderColor =
        self.mouseOrangeColorButton.layer.borderColor =
        self.mousePurpleColorButton.layer.borderColor =
        self.mouseColorButton.layer.borderColor = [NSColor clearColor].CGColor;
        
        sender.layer.borderColor = [KMAppearance KMColor_Interactive_A0].CGColor;
        self.drawView.drawColor = sender.circleColor;
    } else {
        [[NSColorPanel sharedColorPanel] setTarget:self];
        [[NSColorPanel sharedColorPanel] setAction:@selector(ColorPanelColorDidChange:)];
        [[NSColorPanel sharedColorPanel] orderFront:nil];
    }
}

- (void)ColorPanelColorDidChange:(id)sender {
    self.mouseBlackColorButton.layer.borderColor =
    self.mouseRedColorButton.layer.borderColor =
    self.mouseBlueColorButton.layer.borderColor =
    self.mouseGreenColorButton.layer.borderColor =
    self.mouseOrangeColorButton.layer.borderColor =
    self.mousePurpleColorButton.layer.borderColor =
    self.mouseColorButton.layer.borderColor = [NSColor clearColor].CGColor;
    
    CGFloat red,green,blue,alpha;
    NSColor *color = [(NSColorPanel*)sender color];
    [[color colorUsingColorSpaceName:NSCalibratedRGBColorSpace] getRed:&red green:&green blue:&blue alpha:&alpha];
    self.drawView.drawColor = color;
    self.mouseColorButton.layer.borderColor = [NSColor colorWithRed:33.0/255.0 green:124.0/255.0 blue:234.0/255.0 alpha:1.0].CGColor;
}

- (void)keyboardColorPanelColorDidChange:(id)sender {
    self.textBlackColorButton.layer.borderColor =
    self.textRedColorButton.layer.borderColor =
    self.textBlueColorButton.layer.borderColor =
    self.textGreenColorButton.layer.borderColor =
    self.textOrangeColorButton.layer.borderColor =
    self.textPurpleColorButton.layer.borderColor  =
    self.textColorButton.layer.borderColor= [NSColor clearColor].CGColor;
    
    CGFloat red,green,blue,alpha;
    NSColor *color = [NSColorPanel sharedColorPanel].color ? : [NSColor clearColor];
    [[color colorUsingColorSpaceName:NSCalibratedRGBColorSpace] getRed:&red green:&green blue:&blue alpha:&alpha];
    self.keyboardView.keyboardColor = color;
    self.textColorButton.layer.borderColor = [NSColor colorWithRed:33.0/255.0 green:124.0/255.0 blue:234.0/255.0 alpha:1.0].CGColor;
}

#pragma mark - KMDrawViewDelegate Methods

- (void)drawViewDidFinishTouchMode:(KMDrawView *)view {
    [self.trackpadButton.cell setState:0];
    [self.trackpadLabel setHidden:YES];
}

#pragma mark KMChangeSignatureTextDelegate Methods

- (void)changeSignatureText:(BOOL)isTure {
    self.applyButton.enabled = isTure;
}

#pragma mark - show Methods
- (void)didEndSheet:(NSWindow *)sheet returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo {
    if (contextInfo != NULL) {
        void (^handler)(KMSignature*) = (__bridge void(^)(KMSignature*))contextInfo;
        if (handler) {
            handler(self.selectedSignature);
            handler = nil;
        }
    }
}

- (void)beginSheetModalForWindow:(NSWindow *)window completionHandler:(void (^)(KMSignature *signature))handler; {
   
    [NSApp beginSheet:[self window]
       modalForWindow:window
        modalDelegate:self
       didEndSelector:@selector(didEndSheet:returnCode:contextInfo:)
          contextInfo:(__bridge void * _Null_unspecified)(handler ? handler : NULL)];
}

- (void)dismissSheet:(id)sender {
    if (sender) {
        [NSApp endSheet:[self window] returnCode:0];
    } else {
        [NSApp endSheet:[self window] returnCode:1];
    }
    [[self window] orderOut:self];
}

#pragma mark - NSTabViewDelegate Methods

- (BOOL)tabView:(NSTabView *)tabView shouldSelectTabViewItem:(nullable NSTabViewItem *)tabViewItem {
    return YES;
}

- (void)tabView:(NSTabView *)tabView didSelectTabViewItem:(NSTabViewItem *)tabViewItem {
    BOOL isImage = NO;
    if ([tabView indexOfTabViewItem:tabViewItem] == 0) {
        self.type = KMPDFSignatureTypeText;
        if ([self.keyboardView signatureImage]) {
            isImage = YES;
        }
    } else if ([tabView indexOfTabViewItem:tabViewItem] == 1) {
        self.type = KMPDFSignatureTypeInk;
        if ([self.drawView signatureImage]) {
            isImage = YES;
        }
    } else if ([tabView indexOfTabViewItem:tabViewItem] == 2) {
        self.type = KMPDFSignatureTypeImage;
        if ([self.pictureBackView signatureImage]) {
            isImage = YES;
        }
    }
    
    if (isImage) {
        self.applyButton.enabled = YES;
    } else {
        self.applyButton.enabled = NO;
    }
}

#pragma mark - NSNotification

- (void)widthSizeTextFieldNotification:(NSNotification *)notification {
    NSTextView *field = (NSTextView *)notification.object;
    
    if ([field isEqual:_widthSizeTextField]) {
        CGFloat widthSize = [_widthSizeTextField.stringValue floatValue];
        if (widthSize < 0.1) {
            _widthSizeTextField.stringValue = @"0.1";
            _drawView.strokeRadius = _slider.floatValue = 0.1;
        } else if (widthSize > 4) {
            _widthSizeTextField.stringValue = @"4.0";
            _drawView.strokeRadius = _slider.floatValue = 4.0;
        } else {
            _drawView.strokeRadius = _slider.floatValue = widthSize;
        }
    }
}

- (void)themeChanged:(NSNotification *)notification {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self updateViewColor];
    });
}
@end