//
//  CSPluginServices.m
//  CocoaSplit
//
//  Created by Zakk on 11/22/14.
//  Copyright (c) 2014 Zakk. All rights reserved.
//

#import <JavaScriptCore/JavaScriptCore.h>
#import <objc/runtime.h>
#import "CSPluginServices.h"
#import "CAMultiAudioPCMPlayer.h"
#import "CSPcmPlayer.h"
#import "AppDelegate.h"
#import "PreviewView.h"


@implementation CSPluginServices

+(CSPluginServices *) sharedPluginServices
{
    static CSPluginServices *sharedCSPluginServices = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        sharedCSPluginServices = [[self alloc] init];
    });
    
    return sharedCSPluginServices;
}

-(NSString *)generateUUID
{
    CFUUIDRef tmpUUID = CFUUIDCreate(NULL);
    NSString *uuid = (__bridge_transfer NSString *)CFUUIDCreateString(NULL, tmpUUID);
    CFRelease(tmpUUID);
    return uuid;
}



-(JSValue *)runJavascript:(NSString *)script
{
    JSContext *jCtx = [JSContext currentContext];
    if (!jCtx)
    {
        jCtx = [[CaptureController sharedCaptureController] setupJavascriptContext];

    }
    
    return [jCtx evaluateScript:script];
}



-(NSObject *)captureController
{
    return [CaptureController sharedCaptureController];
}

-(NSDate *)streamStartDate
{
    return CaptureController.sharedCaptureController.streamStartDate;
}


-(NSSize)streamSizeHint
{
    return NSMakeSize(CaptureController.sharedCaptureController.activeLayout.canvas_width, CaptureController.sharedCaptureController.activeLayout.canvas_height);
    
}

-(NSArray *)accountNamesForService:(NSString *)serviceName
{
    
    NSString *useServiceName = [NSString stringWithFormat:@"CocoaSplit-%@", serviceName];
    NSMutableDictionary *keyChainAttrs = [[NSMutableDictionary alloc] init];
    
    [keyChainAttrs setObject:(__bridge NSString *)kSecClassGenericPassword forKey:(__bridge NSString *)kSecClass];
    [keyChainAttrs setObject:useServiceName forKey:(__bridge NSString *)kSecAttrService];
    [keyChainAttrs setObject:(id)kCFBooleanTrue forKey:(__bridge NSString *)kSecReturnAttributes];
    [keyChainAttrs setObject:(__bridge id)kSecMatchLimitAll forKey:(__bridge NSString *)kSecMatchLimit];
    
    CFArrayRef resultArray = NULL;
    
    NSMutableArray *retArr = [[NSMutableArray alloc] init];
    
    SecItemCopyMatching((CFDictionaryRef)keyChainAttrs, (CFTypeRef *)&resultArray);
    
    
    if (resultArray)
    {
        for (NSDictionary *itemDict in (__bridge NSArray *)resultArray)
        {
            NSString *accountName = itemDict[(__bridge NSString *)kSecAttrAccount];
            [retArr addObject:accountName];
        }
        
        CFRelease(resultArray);
    }
    return retArr;
}


-(double) currentFPS
{
    AppDelegate *myAppDelegate = [[NSApplication sharedApplication] delegate];
    if (myAppDelegate.captureController)
    {
        return myAppDelegate.captureController.livePreviewView.sourceLayout.frameRate;
    }
    return 0.0;
}


-(int) audioSampleRate
{
    AppDelegate *myAppDelegate = [[NSApplication sharedApplication] delegate];
    if (myAppDelegate.captureController)
    {
        return myAppDelegate.captureController.multiAudioEngine.sampleRate;
    }
    return 0;
}



-(void)loadPythonClass:(NSString *)pyClass fromFile:(NSString *)fromFile withBlock:(void (^)(__unsafe_unretained Class))withBlock
{
    [CaptureController loadPythonClass:pyClass fromFile:fromFile withBlock:withBlock];
}


-(Class)loadPythonClass:(NSString *)pyClass fromFile:(NSString *)fromFile
{
    return [CaptureController loadPythonClass:pyClass fromFile:fromFile];
}

-(NSString *)nameForAudioTrackUUID:(NSString *)uuid
{
    CAMultiAudioEngine *systemEngine = CaptureController.sharedCaptureController.multiAudioEngine;
    NSDictionary *outputTracks = systemEngine.outputTracks;
    CAMultiAudioOutputTrack *outTrack = outputTracks[uuid];
    NSString *trackName = nil;
    if (outTrack)
    {
        trackName = outTrack.name;
    }
    return trackName;
}


-(void)removePCMInput:(CSPcmPlayer *)toRemove
{
    
    CAMultiAudioPCMPlayer *realRemove = (CAMultiAudioPCMPlayer *)toRemove;
    
    
    AppDelegate *myAppDelegate = [[NSApplication sharedApplication] delegate];
    if (myAppDelegate.captureController && myAppDelegate.captureController.multiAudioEngine)
    {
        
        [myAppDelegate.captureController.multiAudioEngine removePCMInput:realRemove];
    }
}


-(CSPcmPlayer *)createPCMInput:(NSString *)forUID withFormat:(const AudioStreamBasicDescription *)withFormat
{
    AppDelegate *myAppDelegate = [[NSApplication sharedApplication] delegate];
    
    
    
    
    if (myAppDelegate.captureController && myAppDelegate.captureController.multiAudioEngine)
    {
        
        CAMultiAudioPCMPlayer *player;
        
        player = [myAppDelegate.captureController.multiAudioEngine createPCMInput:forUID withFormat:withFormat];
        return (CSPcmPlayer *)player;
    }
    
    return nil;
}


-(CSOauth2Authenticator *) createOAuth2Authenticator:(NSString *)serviceName clientID:(NSString *)client_id flowType:(NSString *)flow_type config:(NSDictionary *)config_dict;
{

    return [[CSOauth2Authenticator alloc] initWithServiceName:serviceName clientID:client_id flowType:flow_type config:config_dict];
}


@end
