//=============================================================================================================================
//
// Copyright (c) 2015-2022 VisionStar Information Technology (Shanghai) Co., Ltd. All Rights Reserved.
// EasyAR is the registered trademark or trademark of VisionStar Information Technology (Shanghai) Co., Ltd in China
// and other countries for the augmented reality technology developed by VisionStar Information Technology (Shanghai) Co., Ltd.
//
//=============================================================================================================================

#import "ViewController.h"

#import "OpenGLView.h"

#import <easyar/camera.oc.h>
#import <easyar/engine.oc.h>
#import <easyar/imagetracker.oc.h>
#import <easyar/recorder.oc.h>

@implementation ViewController {
    BOOL started;
    NSString * url;
    UIButton *button_capture;
}

/*
 * Steps to create the key for this sample:
 *  1. login www.easyar.com
 *  2. create app with
 *      Name: HelloARRecording
 *      Bundle ID: cn.easyar.samples.helloarrecording
 *  3. find the created item in the list and show key
 *  4. set key string bellow
 */
NSString * key = @"===PLEASE ENTER YOUR KEY HERE===";

- (void)viewDidLoad
{
    [super viewDidLoad];
    if (![easyar_Engine initialize:key]) {
        NSLog(@"Initialization Failed.");
        [ViewController displayToastWithMessage:[easyar_Engine errorMessage]];
        return;
    }
    if (![easyar_CameraDevice isAvailable]) {
        [ViewController displayToastWithMessage:@"CameraDevice not available."];
        return;
    }
    if (![easyar_ImageTracker isAvailable]) {
        [ViewController displayToastWithMessage:@"ImageTracker not available."];
        return;
    }
    if (![easyar_Recorder isAvailable]) {
        [ViewController displayToastWithMessage:@"Recorder not available."];
        return;
    }
    OpenGLView * view = (OpenGLView *)(self.view);
    [view initialize];
    [view setOrientation:self.interfaceOrientation];

    self->started = NO;
    self->url = @"";

    button_capture = [UIButton buttonWithType:UIButtonTypeSystem];
    button_capture.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height-50, 70, 50);
    [button_capture setTitle:@"CAPTURE" forState:UIControlStateNormal];
    [button_capture addTarget:self action:@selector(button_start_clicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button_capture];
}

+ (NSString*)prepareURL
{
    static long size = 0;
    size ++ ;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDir = [paths objectAtIndex:0];
    NSString *album = [docDir stringByAppendingPathComponent:@"album"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:album]) {
        NSLog(@"first run");
        [[NSFileManager defaultManager] createDirectoryAtPath:album withIntermediateDirectories:YES attributes:nil error:nil];
        NSLog(@"%@",album);
    }
    double timenumber = [NSDate date].timeIntervalSince1970;
    NSLog(@"timenumber %lf",timenumber);
    NSString *time = [NSString stringWithFormat:@"%lf",timenumber];
    time = [time stringByReplacingOccurrencesOfString:@"." withString:@"mm"];
    NSLog(@"%@",time);
    NSString *videoString = [NSString stringWithFormat:@"%@number%08ld.mp4",time,size];
    NSString *path = [NSString stringWithFormat:@"%@/%@",album,videoString];
    NSLog(@"path %@",path);
    return path;
}

- (void)button_start_clicked
{
    if (started) {
        OpenGLView * view = (OpenGLView *)(self.view);
        [view stopRecording];
        [ViewController displayToastWithMessage:[@"Recorded at " stringByAppendingString:url]];
        started = NO;
        [button_capture setTitle:@"CAPTURE" forState:UIControlStateNormal];
        return;
    }
    OpenGLView * view = (OpenGLView *)(self.view);
    [view requestPermissions:^(easyar_PermissionStatus status, NSString * msg) {
        switch (status) {
            case easyar_PermissionStatus_Denied:
                started = NO;
                [button_capture setTitle:@"CAPTURE" forState:UIControlStateNormal];
                [ViewController displayToastWithMessage:@"Permission Denied"];
                break;
            case easyar_PermissionStatus_Error:
                started = NO;
                [button_capture setTitle:@"CAPTURE" forState:UIControlStateNormal];
                [ViewController displayToastWithMessage:@"Permission Error"];
                break;
            case easyar_PermissionStatus_Granted:
                url = [ViewController prepareURL];
                {
                    __weak ViewController * weak_self = self;
                    OpenGLView * view = (OpenGLView *)(self.view);
                    [view startRecording:url callback:^(easyar_RecordStatus status, NSString *value) {
                        if (status == easyar_RecordStatus_OnStopped) {
                            ViewController * strong_self = weak_self;
                            strong_self->started = NO;
                            [strong_self->button_capture setTitle:@"CAPTURE" forState:UIControlStateNormal];
                        }
                        NSLog(@"Recorder Callback status: %d, MSG: %@", (int)(status), value);
                    }];
                }
                [ViewController displayToastWithMessage:@"Recording..."];
                break;
            default:
                break;
        }
    }];
    started = YES;
    [button_capture setTitle:@"STOP" forState:UIControlStateNormal];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    OpenGLView * view = (OpenGLView *)(self.view);
    [view start];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    OpenGLView * view = (OpenGLView *)(self.view);
    [view stop];
}

-(void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    if (started) {
        OpenGLView * view = (OpenGLView *)(self.view);
        [view stopRecording];
        [ViewController displayToastWithMessage:[@"Recorded at " stringByAppendingString:url]];
        started = NO;
    }
    button_capture.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height-50, 70, 50);
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
    OpenGLView * view = (OpenGLView *)(self.view);
    [view setOrientation:toInterfaceOrientation];
}

+ (void)displayToastWithMessage:(NSString *)toastMessage
{
    [[NSOperationQueue mainQueue] addOperationWithBlock:^ {
        UIWindow * keyWindow = [[UIApplication sharedApplication] keyWindow];
        UILabel * toastView = [[UILabel alloc] init];
        toastView.text = toastMessage;
        toastView.textAlignment = NSTextAlignmentCenter;
        toastView.textColor = [UIColor whiteColor];
        toastView.lineBreakMode = NSLineBreakByWordWrapping;
        toastView.numberOfLines = 0;
        toastView.frame = CGRectMake(0.0, 0.0, keyWindow.frame.size.width/2.0, 200.0);
        toastView.layer.cornerRadius = 10;
        toastView.layer.masksToBounds = YES;
        toastView.center = keyWindow.center;
        
        [keyWindow addSubview:toastView];
        
        [UIView animateWithDuration: 0.5f
                              delay: 3.0f
                            options: UIViewAnimationOptionCurveLinear
                         animations: ^{
                             toastView.alpha = 0.0f;
                         }
                         completion: ^(BOOL finished) {
                             [toastView removeFromSuperview];
                         }
         ];
    }];
}

@end
