#import <Foundation/Foundation.h>
#import <AppKit/NSPasteboard.h>
#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
#include "clipboard.h"

long change_count = 0;

#define ART_GVM_CLIPFORMAT "com.microsoft.Art--GVML-ClipFormat"

char* MacGetClipboard(MacClipboardFormat *format, unsigned *len) {
    if (len) *len=0;
    NSPasteboard *pasteboard= [NSPasteboard generalPasteboard];
    const long count = [pasteboard changeCount];
    if (count == change_count) {
        *format = MacClipboardFormat::No_Change;
        *len = 0;
        return 0;
    }
    change_count = count;


    for (NSPasteboardItem *item in [pasteboard pasteboardItems])
        for (NSString *type in [item types])
            if ([type isEqualToString:NSPasteboardTypeString]) {
                NSString* content = [item stringForType:NSPasteboardTypeString];
                if ([content hasPrefix:@"Msc-generator~|"]) {
                    if (format) *format = MacClipboardFormat::Escaped_Text;
                    if (len) *len = [content length];
                    char *data = (char*)malloc([content length]);
                    if (data) memcpy(data, [content UTF8String], [content length]);
                    return data;
                }
            } else if ([type isEqualToString:@ART_GVM_CLIPFORMAT]) {
                NSData *data = [item dataForType:type];
                if (data) {
                    if (format) *format = MacClipboardFormat::Art_GVML;
                    if (len) *len = [data length];
                    char *ret = (char*)malloc([data length]);
                    if (ret) memcpy(ret, [data bytes], [data length]);
                    return ret;
                }
            } else {
                *format = MacClipboardFormat::Else;
                *len = 0;
                return 0;
            }
    return 0;
}

int MacCopyToClipboard(MacClipboardFormat format, const char *content, unsigned content_len, const char *type)
{
    if (!content || !content_len || !type) return 1;
    NSPasteboard *pasteboard= [NSPasteboard generalPasteboard];
    switch (format) {
    default:
        return 1; //dont try again
    case MacClipboardFormat::Escaped_Text:
        change_count = [pasteboard clearContents];
        return [pasteboard setString:[NSString stringWithUTF8String:content] forType:NSPasteboardTypeString];
    case MacClipboardFormat::Art_GVML:
        change_count = [pasteboard clearContents];
        if (![pasteboard setData:[NSData dataWithBytesNoCopy:(void*)content length:content_len freeWhenDone:NO] forType:@ART_GVM_CLIPFORMAT])
            return 0;
        //TODO: Add object descriptor @"com.microsoft.Object-Descriptor"
        return 1;
    }
}
