//
//  KMAnnotationFontWindowController.m
//  SignFlow
//
//  Created by wanjun on 2021/6/22.
//

#import "KMAnnotationFontWindowController.h"
//#import "NSUserDefaults_SKExtensions.h"
#import "NSFont_SKExtensions.h"

@interface KMAnnotationFontWindowController ()

@property (assign) IBOutlet NSBox *lineBox;

@property (assign) IBOutlet NSTextField *fontLabel;
@property (assign) IBOutlet NSComboBox *fontComboBox;
@property (assign) IBOutlet NSTextField *fontWeightLabel;
@property (assign) IBOutlet NSPopUpButton *fontWeightPopUpButton;
@property (assign) IBOutlet NSTextField *fontSizeLabel;
@property (assign) IBOutlet NSPopUpButton *fontSizePopUpButton;
@property (assign) IBOutlet NSTextField *fontColorLabel;
@property (assign) IBOutlet NSColorWell *fontColorWell;

@property (assign) IBOutlet NSTextField *fontAdjacencyLabel;
@property (assign) IBOutlet NSBox *fontAdjacencyBox;
@property (assign) IBOutlet NSTextField *fontAdjacencyBoxLabel;
@property (assign) IBOutlet NSStepper *fontAdjacencyStepper;

@property (assign) IBOutlet NSTextField *rowHeightLabel;
@property (assign) IBOutlet NSBox *rowHeightBox;
@property (assign) IBOutlet NSTextField *rowHeightBoxLabel;
@property (assign) IBOutlet NSStepper *rowHeightStepper;

@property (assign) IBOutlet NSTextField *alignmentLabel;
@property (assign) IBOutlet NSSegmentedControl *alignmentSegmentedControl;

@property (assign) IBOutlet NSLayoutConstraint *fontAdjacencyLayoutConstraint;
@property (assign) IBOutlet NSLayoutConstraint *rowHeightLayoutConstraint;
@property (assign) IBOutlet NSLayoutConstraint *alignmenBottomConstraint;

@property (nonatomic, retain) NSMutableArray*fonts;

@end

static KMAnnotationFontWindowController *sharedAnnotationFont = nil;

@implementation KMAnnotationFontWindowController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

+ (id)sharedAnnotationFont {
    if (sharedAnnotationFont == nil)
        sharedAnnotationFont = [[self alloc] init];
    return sharedAnnotationFont;
}

- (id)init {
    self = [super initWithWindowNibName:@"KMAnnotationFontWindowController"];
    if (self) {
        
    }
    return self;
}

- (void)windowDidLoad {
    [super windowDidLoad];
    
    self.fonts = [NSFont supportFonts];
    
    self.window.title = NSLocalizedString(@"Fonts", nil);
    
    self.fontLabel.stringValue = [NSString stringWithFormat:@"%@:",NSLocalizedString(@"Fonts", nil)];
    self.fontWeightLabel.stringValue = [NSString stringWithFormat:@"%@:",NSLocalizedString(@"Font Weight", nil)];
    self.fontSizeLabel.stringValue = [NSString stringWithFormat:@"%@:",NSLocalizedString(@"Font Size", nil)];
    self.fontColorLabel.stringValue = [NSString stringWithFormat:@"%@:",NSLocalizedString(@"Text Color", nil)];
    self.fontAdjacencyLabel.stringValue = [NSString stringWithFormat:@"%@:",NSLocalizedString(@"Font Adjacency", nil)];
    self.rowHeightLabel.stringValue = [NSString stringWithFormat:@"%@:",NSLocalizedString(@"Row Height", nil)];
    self.alignmentLabel.stringValue = [NSString stringWithFormat:@"%@:",NSLocalizedString(@"Alignment", nil)];
    if (@available(macOS 10.13, *)) {
        [self.alignmentSegmentedControl setToolTip:NSLocalizedString(@"Left Alignment", nil) forSegment:0];
        [self.alignmentSegmentedControl setToolTip:NSLocalizedString(@"Center", nil) forSegment:1];
        [self.alignmentSegmentedControl setToolTip:NSLocalizedString(@"Right Alignment", nil) forSegment:2];
    }
    [self.alignmentSegmentedControl.cell setControlTint:NSClearControlTint];
    self.fontAdjacencyStepper.hidden = YES;
    self.rowHeightStepper.hidden = YES;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alignmentTypeNotification:) name:@"KMAnnotationAlignmentTypeNotification" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(fontTypeNotification:) name:@"KMAnnotationFontTypeNotification" object:nil];    
}

#pragma mark - View Methods

-(void)setAnnotationModel:(CPDFAnnotationModel *)annotationModel
{
    if (_annotationModel != annotationModel) {
        _annotationModel = annotationModel;
    }
    [self reloadData];
}

- (void)reloadData {
    NSFont *notefont = [NSFont fontWithName:self.annotationModel.fontName size:self.annotationModel.fontSize];
    NSColor *noteColor = self.annotationModel.fontColor;
    if (noteColor) {
        CGFloat r, g, b, a = 0.0;
        [[noteColor colorUsingColorSpaceName:NSDeviceRGBColorSpace] getRed:&r green:&g blue:&b alpha:&a];
        noteColor = [NSColor colorWithRed:r green:g blue:b alpha:self.annotationModel.opacity];
    }
    if (CAnnotationTypeFreeText == self.annotationModel.annotationType ||
        CAnnotationTypeSignText == self.annotationModel.annotationType ||
        CAnnotationTypeSignDate == self.annotationModel.annotationType ||
        CAnnotationTypeTextField  == self.annotationModel.annotationType) {
        if (self.annotationModel.alignment == NSTextAlignmentLeft) {
            [self.alignmentSegmentedControl setImage:[NSImage imageNamed:@"KMImageNamePropertybarTextalignLeftOtherSel"] forSegment:0];
            if (@available(macOS 11.0, *))  {
                [self.alignmentSegmentedControl setImage:[NSImage imageNamed:@"KMImageNamePropertybarTextalignLeftSel"] forSegment:0];
            }
            [self.alignmentSegmentedControl setImage:[NSImage imageNamed:@"KMImageNamePropertybarTextalignCenterNor"] forSegment:1];
            [self.alignmentSegmentedControl setImage:[NSImage imageNamed:@"KMImageNamePropertybarTextalignRightNor"] forSegment:2];
            self.alignmentSegmentedControl.selectedSegment = 0;
        } else if (self.annotationModel.alignment == NSTextAlignmentCenter) {
            [self.alignmentSegmentedControl setImage:[NSImage imageNamed:@"KMImageNamePropertybarTextalignLeftNor"] forSegment:0];
            [self.alignmentSegmentedControl setImage:[NSImage imageNamed:@"KMImageNamePropertybarTextalignCenterOtherSel"] forSegment:1];
            if (@available(macOS 11.0, *))  {
                [self.alignmentSegmentedControl setImage:[NSImage imageNamed:@"KMImageNamePropertybarTextalignCenterSel"] forSegment:1];
            }
            [self.alignmentSegmentedControl setImage:[NSImage imageNamed:@"KMImageNamePropertybarTextalignRightNor"] forSegment:2];
            self.alignmentSegmentedControl.selectedSegment = 1;
        } else if (self.annotationModel.alignment == NSTextAlignmentRight) {
            [self.alignmentSegmentedControl setImage:[NSImage imageNamed:@"KMImageNamePropertybarTextalignLeftNor"] forSegment:0];
            [self.alignmentSegmentedControl setImage:[NSImage imageNamed:@"KMImageNamePropertybarTextalignCenterNor"] forSegment:1];
            [self.alignmentSegmentedControl setImage:[NSImage imageNamed:@"KMImageNamePropertybarTextalignRightOtherSel"] forSegment:2];
            if (@available(macOS 11.0, *))  {
                [self.alignmentSegmentedControl setImage:[NSImage imageNamed:@"KMImageNamePropertybarTextalignRightSel"] forSegment:2];
            }
            self.alignmentSegmentedControl.selectedSegment = 2;
        } else if (self.annotationModel.alignment == NSTextAlignmentJustified) {
            [self.alignmentSegmentedControl setImage:[NSImage imageNamed:@"KMImageNamePropertybarTextalignLeftNor"] forSegment:0];
            [self.alignmentSegmentedControl setImage:[NSImage imageNamed:@"KMImageNamePropertybarTextalignCenterNor"] forSegment:1];
            [self.alignmentSegmentedControl setImage:[NSImage imageNamed:@"KMImageNamePropertybarTextalignRightNor"] forSegment:2];
            self.alignmentSegmentedControl.selectedSegment = 3;
        }
    }
    
    [self.fontWeightPopUpButton removeAllItems];
    self.fontSizePopUpButton.title = [NSString stringWithFormat:@"%@ pt",@(notefont.pointSize)];
    
    NSDictionary * dic = nil;
    NSMutableArray * fontNames = [NSMutableArray array];
    for (NSUInteger i=0; i<self.fonts.count; i++) {
        NSDictionary *fontDic = self.fonts[i];
        NSString * fontName = fontDic.allKeys.firstObject?:@"Helvetica";
        NSString * family =   [notefont.fontDescriptor objectForKey:NSFontFamilyAttribute];
        [fontNames addObject:fontName];
        if ([family isEqualToString:fontName]) {
            dic = fontDic;
        }
    }
    NSString * style =   [notefont.fontDescriptor objectForKey:NSFontFaceAttribute];
    [self.fontComboBox removeAllItems];
    [self.fontComboBox addItemsWithObjectValues:fontNames];
        
    if (dic) {
        NSInteger selectedIndex = [self.fonts indexOfObject:dic];
        [self.fontComboBox selectItemAtIndex:selectedIndex];

        NSString * fontName = dic.allKeys.firstObject;
        NSInteger selectIndex = [self setFontStyleWithFontName:fontName currentStyle:style];
        if (selectIndex != -1) {
            [self.fontWeightPopUpButton selectItemAtIndex:selectIndex];
        } else {
            [self.fontWeightPopUpButton setTitle:@""];
        }
    } else{
        [self.fontWeightPopUpButton setTitle:@""];
        [self.fontWeightPopUpButton setTitle:@""];
    }
    self.fontColorWell.color = noteColor?:[NSColor clearColor];
    [[NSColorPanel sharedColorPanel] setTarget:self];
    [[NSColorPanel sharedColorPanel] setAction:nil];
    
    self.fontAdjacencyLayoutConstraint.constant = self.fontAdjacencyStepper.hidden ? -self.fontAdjacencyStepper.frame.size.height : 16.0;
    self.fontAdjacencyBox.hidden = self.fontAdjacencyStepper.hidden ? YES : NO;
    self.fontAdjacencyLabel.hidden = self.fontAdjacencyStepper.hidden ? YES : NO;
    self.rowHeightLayoutConstraint.constant = self.rowHeightStepper.hidden ? -self.rowHeightStepper.frame.size.height + 11.0 : 11.0;
    self.rowHeightBox.hidden = self.rowHeightStepper.hidden ? YES : NO;
    self.rowHeightLabel.hidden = self.rowHeightStepper.hidden ? YES : NO;
    
    if (CAnnotationTypeComboBox == self.annotationModel.annotationType || CAnnotationTypeListMenu == self.annotationModel.annotationType) {
        self.alignmentSegmentedControl.hidden = self.alignmentLabel.hidden = self.lineBox.hidden = YES;
        
        self.alignmenBottomConstraint.constant = 0;
    } else {
        self.alignmentSegmentedControl.hidden = self.lineBox.hidden = self.alignmentLabel.hidden = NO;
        self.alignmenBottomConstraint.constant = 46;

    }
}

#pragma mark - private

-(NSUInteger)setFontStyleWithFontName:(NSString *)fontName currentStyle:(NSString *)style
{
    NSUInteger selectIndex = -1;
    NSMenu *menu = [[NSMenu alloc] init];
    for (NSDictionary *dic in self.fonts) {
        NSString *familyString = dic.allKeys.firstObject;
        if ([familyString isEqual:fontName]) {
            NSArray *styles = [dic objectForKey:fontName];
            for (NSUInteger i = 0; i < styles.count; i++) {
                NSString * styleName = [styles objectAtIndex:i];
                if ([style isEqualToString:styleName]) {
                    selectIndex = i;
                }
                NSFontDescriptor *attributeFontDescriptor = [NSFontDescriptor fontDescriptorWithFontAttributes:@{NSFontFamilyAttribute:fontName,NSFontFaceAttribute:styleName}];
                NSFont *font = [NSFont fontWithDescriptor:attributeFontDescriptor size:12.0];
                NSDictionary *attrited = @{NSFontAttributeName:font};
                NSAttributedString *string = [[NSAttributedString alloc] initWithString:styleName attributes:attrited];
                NSMenuItem *item = [[NSMenuItem alloc] init];
                item.attributedTitle = string;
                
                [menu addItem:item];
            }
            break;
        }
    }
    if (!style) {
        selectIndex = 0;
    }
    [self.fontWeightPopUpButton setMenu:menu];
    
    return selectIndex;
}

#pragma mark - Action

- (IBAction)fontComboBoxAction:(NSComboBox *)sender {
    NSInteger selectItem = [self.fontComboBox indexOfSelectedItem];
    NSString * familyString = [self.fontComboBox itemObjectValueAtIndex:selectItem];
    NSInteger selectIndex = [self setFontStyleWithFontName:familyString currentStyle:nil];
    NSString * styleString = self.fontWeightPopUpButton.selectedItem.title;
    if (selectIndex != -1) {
        [self.fontWeightPopUpButton selectItemAtIndex:selectIndex];
    }
    
    if (self.annotationFreeText) {
        [self.annotationFreeText setFont:[NSFont fontWithName:[NSString stringWithFormat:@"%@-%@",familyString,[styleString stringByReplacingOccurrencesOfString:@" " withString:@""]] size:self.annotationFreeText.font.pointSize]];
    } else {
        self.annotationModel.fontName = [NSString stringWithFormat:@"%@-%@",familyString,[styleString stringByReplacingOccurrencesOfString:@" " withString:@""]];
    }
    if (self.annotationCallback) {
        self.annotationCallback(self.annotationModel.annotation);
    }
}

- (IBAction)fontSizeComboBoxAction:(NSPopUpButton *)sender
{
    CGFloat fontSize = [[self.fontSizePopUpButton.title stringByReplacingOccurrencesOfString:@" pt" withString:@""] floatValue];
    if (self.annotationFreeText) {
        [self.annotationFreeText setFont:[NSFont fontWithName:self.annotationFreeText.font.fontName size:fontSize]];
    } else {
        self.annotationModel.fontSize = fontSize;

    }
    if (self.annotationCallback) {
        self.annotationCallback(self.annotationModel.annotation);
    }
}

//字重 NSFontWeight
- (IBAction)fontStylePopUpButtonAction:(NSPopUpButton *)sender {
    NSString * styleString = self.fontWeightPopUpButton.selectedItem.title;
    NSFont *font = [NSFont fontWithName:self.annotationModel.fontName size:self.annotationModel.fontSize];
    NSString * familyString = [font.fontDescriptor objectForKey:NSFontFamilyAttribute];
    if (self.annotationFreeText) {
        [self.annotationFreeText setFont:[NSFont fontWithName:[NSString stringWithFormat:@"%@-%@",familyString,[styleString stringByReplacingOccurrencesOfString:@" " withString:@""]] size:self.annotationFreeText.font.pointSize]];
    } else {
        self.annotationModel.fontName = [NSString stringWithFormat:@"%@-%@",familyString,[styleString stringByReplacingOccurrencesOfString:@" " withString:@""]];
    }
    if (self.annotationCallback) {
        self.annotationCallback(self.annotationModel.annotation);
    }
}

- (IBAction)fontColorWellAction:(NSColorWell *)sender {
    
    NSColor *currentColor = sender.color;
    CGFloat r, g, b, a = 0.0;
    [[currentColor colorUsingColorSpaceName:NSDeviceRGBColorSpace] getRed:&r green:&g blue:&b alpha:&a];
    if (self.annotationFreeText) {
        if (fabs(a - 0) < 0.001) {
            //设置透明色必须要设一个颜色值
            self.annotationFreeText.fontColor = [NSColor blackColor];
            self.annotationFreeText.opacity = 0;
        } else {
            self.annotationFreeText.fontColor = currentColor;
            self.annotationFreeText.opacity = a;
        }
    } else {
        if (fabs(a - 0) < 0.001) {
            //设置透明色必须要设一个颜色值
            self.annotationModel.fontColor = [NSColor blackColor];
            self.annotationModel.opacity = 0;
        } else {
            self.annotationModel.fontColor = currentColor;
            self.annotationModel.opacity = a;
        }
    }
    if (self.annotationCallback) {
        self.annotationCallback(self.annotationModel.annotation);
    }
}

- (IBAction)alignButtonAction:(NSSegmentedControl *)sender {
    NSInteger alignCount = [self reloadSegmentControlImage:sender.selectedSegment];
    if (self.annotationFreeText) {
        self.annotationFreeText.alignment = alignCount;
    }
    if (self.annotationAlignCallback) {
        self.annotationAlignCallback(alignCount);
    }
}

- (NSInteger)reloadSegmentControlImage:(NSInteger)selectedIndex {
    NSInteger alignCount = 0;
    switch (selectedIndex) {
        case 0:
            alignCount = 0;
            self.annotationModel.alignment = NSTextAlignmentLeft;
            [self.alignmentSegmentedControl setImage:[NSImage imageNamed:@"KMImageNamePropertybarTextalignLeftOtherSel"] forSegment:0];
            if (@available(macOS 11.0, *))  {
                [self.alignmentSegmentedControl setImage:[NSImage imageNamed:@"KMImageNamePropertybarTextalignLeftSel"] forSegment:0];
            }
            [self.alignmentSegmentedControl setImage:[NSImage imageNamed:@"KMImageNamePropertybarTextalignCenterNor"] forSegment:1];
            [self.alignmentSegmentedControl setImage:[NSImage imageNamed:@"KMImageNamePropertybarTextalignRightNor"] forSegment:2];
            [self.alignmentSegmentedControl setImage:[NSImage imageNamed:@"KMImageNamePropertybarTextalignJustifyNor"] forSegment:3];
            break;
        case 1:
            alignCount = 2;
            self.annotationModel.alignment = NSTextAlignmentCenter;
            [self.alignmentSegmentedControl setImage:[NSImage imageNamed:@"KMImageNamePropertybarTextalignLeftNor"] forSegment:0];
            [self.alignmentSegmentedControl setImage:[NSImage imageNamed:@"KMImageNamePropertybarTextalignCenterOtherSel"] forSegment:1];
            if (@available(macOS 11.0, *))  {
                [self.alignmentSegmentedControl setImage:[NSImage imageNamed:@"KMImageNamePropertybarTextalignCenterSel"] forSegment:1];
            }
            [self.alignmentSegmentedControl setImage:[NSImage imageNamed:@"KMImageNamePropertybarTextalignRightNor"] forSegment:2];
            [self.alignmentSegmentedControl setImage:[NSImage imageNamed:@"KMImageNamePropertybarTextalignJustifyNor"] forSegment:3];
            break;
        case 2:
            alignCount = 1;
            self.annotationModel.alignment = NSTextAlignmentRight;
            [self.alignmentSegmentedControl setImage:[NSImage imageNamed:@"KMImageNamePropertybarTextalignLeftNor"] forSegment:0];
            [self.alignmentSegmentedControl setImage:[NSImage imageNamed:@"KMImageNamePropertybarTextalignCenterNor"] forSegment:1];
            [self.alignmentSegmentedControl setImage:[NSImage imageNamed:@"KMImageNamePropertybarTextalignRightOtherSel"] forSegment:2];
            if (@available(macOS 11.0, *))  {
                [self.alignmentSegmentedControl setImage:[NSImage imageNamed:@"KMImageNamePropertybarTextalignRightSel"] forSegment:2];
            }
            [self.alignmentSegmentedControl setImage:[NSImage imageNamed:@"KMImageNamePropertybarTextalignJustifyNor"] forSegment:3];
            break;
        default:
            break;
    }
    return alignCount;
}

#pragma mark - notification

- (void)alignmentTypeNotification:(NSNotification *)notification {
    NSString *count = notification.object;
    
    if ([count isEqualToString:@"0"]) {
        self.alignmentSegmentedControl.selectedSegment = 0;
        
    } else if ([count isEqualToString:@"1"]) {
        self.alignmentSegmentedControl.selectedSegment = 2;
    } else if ([count isEqualToString:@"2"]) {
        self.alignmentSegmentedControl.selectedSegment = 1;
    }
    [self reloadSegmentControlImage:self.alignmentSegmentedControl.selectedSegment];
}

- (void)fontTypeNotification:(NSNotification *)notification
{
    if (notification.object == self.PDFListView) {
        [self reloadData];
    }
}

@end