//
//  Logger.m
//  RNRainbowRn
//
//  Created by Doha Tubaileh on 8/6/19.
//  Copyright © 2019 Facebook. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>
#import "Logger.h"
#import <React/RCTLog.h>
#import "Rainbow/Rainbow.h"
#import "IEventEmmiter.h"
#import "LoggerEventsNames.h"
#import "LogFileManager.h"
#import "RNRainbowRn.h"
#import <MessageUI/MessageUI.h>

#define AppName @"Rainbow React-Native Module"

@interface Logger ()
@property (nonatomic, strong) NSURL *applicationLogUrl;
@property (nonatomic, strong) IEventEmmiter *eventEmitter;
@property (nonatomic, weak) RCTBridge *bridge;

@end

@implementation Logger

RCT_EXPORT_MODULE();

- (instancetype)init
{
    self = [super init];
    if (self) {
    }
    return self;
}

RCT_EXPORT_METHOD(error:(NSString *)tag _:(NSString *)msg) {
    NSLog(@"[%@] %@",tag,msg);
}
RCT_EXPORT_METHOD(info:(NSString *)tag _:(NSString *)msg) {
    NSLog(@"[%@] %@",tag,msg);
}

RCT_EXPORT_METHOD(warn:(NSString *)tag _:(NSString *)msg) {
    NSLog(@"[%@] %@",tag,msg);
}

RCT_EXPORT_METHOD(debug:(NSString *)tag _:(NSString *)msg) {
    NSLog(@"[%@] %@",tag,msg);
}

RCT_EXPORT_METHOD(getAppVersion) {
    NSString *appVersion = [Tools applicationVersion];
    [self sendEventWithName:AppVersion eventBody:appVersion];
}

RCT_EXPORT_METHOD(sendLogs) {
    [self sendLogsByMail];
}

+(void) startRecordingLogs {
    
    BOOL amIDebugging = [self checkIfInDebuggingMode];

    if (!amIDebugging) {
        // Remove logs file older than 2 days.
        [[LogsRecorder sharedInstance] cleanOldLogs] ;
        [[LogsRecorder sharedInstance] stopRecord];
        [[LogsRecorder sharedInstance] startRecord];
    }
    
}

+(void) stopRecordingLogs {
    BOOL amIDebugging = [self checkIfInDebuggingMode];
    
    if (!amIDebugging) {
        [[LogsRecorder sharedInstance] stopRecord];
    }
}

+ (BOOL)requiresMainQueueSetup {
    return NO;
}

+(BOOL)checkIfInDebuggingMode {
    NSLog(@"[Logger]checkIfInDebuggingMode");
    
#if DEBUG
    NSLog(@"[Logger] deugging mode");
    return YES;
#else
    NSLog(@"[Logger] non-deugging mode");
#endif
    
    return NO;
}

- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
    [[[RNRainbowRn sharedManager] navigationController] dismissViewControllerAnimated:YES completion:nil];
}

- (void) sendLogsByMail {
    NSLog(@"[LogFileManager] sendLogFileByMail");
    // If no configure mail account
    if (![MFMailComposeViewController canSendMail]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Could not send mail", nil) message:NSLocalizedString(@"No configured mail account", nil) preferredStyle:UIAlertControllerStyleAlert];
            alertController.view.accessibilityIdentifier = @"errorAlert";
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", nil) style:UIAlertActionStyleCancel handler:nil];
            [alertController addAction:okAction];
            [[[RNRainbowRn sharedManager] navigationController] presentViewController:alertController animated:YES completion:nil];
        });
        return;
    }
    // Stop record before zipping to got the complete file
    [[LogsRecorder sharedInstance] stopRecord];
    _applicationLogUrl = [[LogsRecorder sharedInstance] zippedApplicationLogs];
    if (!_applicationLogUrl) {
        [[LogsRecorder sharedInstance] startRecord];
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Could not send mail", nil) message:NSLocalizedString(@"No logs file found.", nil) preferredStyle:UIAlertControllerStyleAlert];
            alertController.view.accessibilityIdentifier = @"errorAlert";
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", nil) style:UIAlertActionStyleCancel handler:nil];
            [alertController addAction:okAction];
            [[[RNRainbowRn sharedManager] navigationController]  presentViewController:alertController animated:YES completion:nil];
        });
        return;
    }
    // restat record after zipping
    NSError *dataError = nil;
    NSData *attachmentData = [NSData dataWithContentsOfFile:_applicationLogUrl.path options:0 error:&dataError];
    
    [self openMailBrowserWithLogsData:attachmentData];
    
}
-(void)openMailBrowserWithLogsData:(NSData *)attachmentData {
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd_HH:mm:ss"];
    NSString* date = [dateFormatter stringFromDate:[NSDate date]];
    
    NSString* bodyContent = [NSString stringWithFormat:@"\n\n\n%@\n------\nProduct : %@\nVersion: %@\n Date: %@\niOS version : %@", NSLocalizedString(@"Do not modify anythings below this line", nil), AppName, [Tools applicationVersion], date, [UIDevice currentDevice].systemVersion];
    NSString* attachedFileName = [NSString stringWithFormat:@"%@-%@-logs.txt.zip", AppName, [Tools applicationVersion]];
    
    // Compute username
    NSString* userName = [ServicesManager sharedInstance].myUser.username;
    
    // Send logs
    MFMailComposeViewController *mailComposer = [[MFMailComposeViewController alloc] init];
    mailComposer.mailComposeDelegate = self;
    [mailComposer setSubject:[NSString stringWithFormat:@"%@ %@ %@ application logs for user %@",[Tools applicationName], [Tools applicationVersion], [Tools currentOS], userName]];
    [mailComposer setMessageBody:bodyContent isHTML:NO];
    if (attachmentData)
        [mailComposer addAttachmentData:attachmentData mimeType:@"application/x-gzip" fileName:attachedFileName];
    [[[RNRainbowRn sharedManager] navigationController] presentViewController:mailComposer animated:YES completion:nil];
}

- ( IEventEmmiter *)eventEmitter {
    if (!_eventEmitter) {
        _eventEmitter = [self.bridge moduleForClass:[IEventEmmiter class]];
    }
    return _eventEmitter;
}

- (void)sendEventWithName:(NSString *)eventName eventBody:(id)eventBody {
    IEventEmmiter *eventEmitter = [self eventEmitter];
    if (eventEmitter) {
        NSLog(@" [Logger] sendEventWithName: %@", eventName);
        [eventEmitter sendEvent:eventName eventBody:eventBody];
    } else {
        NSLog(@"[Logger] sendEventWithName:  Bridge is not ready. Cannot send event: %@", eventName);
    }
}
@end
