//
//  LogFileManager.m
//  rainbow
//
//  Created by Doha Tubaileh on 1/29/20.
//  Copyright © 2020 Facebook. All rights reserved.
//

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

#define AppName @"Rainbow_example"

@interface LogFileManager ()
@property (nonatomic, strong) NSURL *applicationLogUrl;
@end


@implementation LogFileManager
RCT_EXPORT_MODULE();

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


// Then implement the delegate method
- (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];
}

+ (BOOL)requiresMainQueueSetup
{
    return NO;
}
@end
