//
//  ImageUploadViewController.m
//  RedAnt ERP Mobile
//
//  Created by Ray on 11/4/15.
//  Copyright © 2015 United Software Applications, Inc. All rights reserved.
//

#import "ImageUploadViewController.h"

#import "UIProgressView+AFNetworking.h"
#import "AFHTTPSessionManager.h"

#import "config.h"
#import "RAUtils.h"
#import "AppDelegate.h"
#import "OLDataProvider.h"

//#import "UIAlertView+AFNetworking.h"

#define TEST_URL @"http://192.168.1.3:8080/ios_server/ul.jsp"
@interface ImageUploadViewController ()

@end

@implementation ImageUploadViewController




-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    UIApplication * app = [UIApplication sharedApplication];
    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
    [appDelegate didRotated];
    
    //    [CATransaction begin];
    //    [CATransaction setAnimationDuration:0.5];
    //    [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    //    //    [self updatePreviewLayerForOrientation:toInterfaceOrientation];
    //    _previewLayer.position = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));
    //
    //    //   self.backgroundView.highLightRect = CGRectInset(self.focusZone.frame,6,6);
    //    _previewLayer.bounds = rect;
    //
    //    UIInterfaceOrientation orientation = [[UIApplication sharedApplication]statusBarOrientation];
    //    switch (orientation) {
    //
    //
    //
    //        case UIInterfaceOrientationPortrait:
    //            // [_previewLayer setAffineTransform:CGAffineTransformMakeRotation(0)];
    //
    //            _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationPortrait;
    //            break;
    //        case UIInterfaceOrientationPortraitUpsideDown:
    //            //[_previewLayer setAffineTransform:CGAffineTransformMakeRotation(M_PI)];
    //            _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationPortraitUpsideDown;
    //            break;
    //        case UIInterfaceOrientationLandscapeLeft:
    //            // [_previewLayer setAffineTransform:CGAffineTransformMakeRotation(M_PI/2)];
    //            _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationLandscapeLeft;
    //            break;
    //        case UIInterfaceOrientationLandscapeRight:
    //            // [_previewLayer setAffineTransform:CGAffineTransformMakeRotation(-M_PI/2)];
    //            _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationLandscapeRight;
    //            break;
    //        default:
    //            break;
    //    }
    //    [CATransaction commit];
    
    
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:animationDuration];
    
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication]statusBarOrientation];
    if (UIInterfaceOrientationIsLandscape(orientation))
    {
        
        
        self.buttonAlbum.frame = CGRectMake(942,120,48,48);
        self.buttonCamera.frame = CGRectMake(942,200,48,48);
        self.buttonUpload.frame = CGRectMake(942,363,48,48);
        //        @property (strong, nonatomic) IBOutlet UIButton *buttonAlbum;
        //        @property (strong, nonatomic) IBOutlet UIButton *buttonCamera;
        //        @property (strong, nonatomic) IBOutlet UIButton *buttonUpload;
    }
    else
    {
        self.buttonAlbum.frame = CGRectMake(82,918,48,48);
        self.buttonCamera.frame = CGRectMake(173,918,48,48);
        self.buttonUpload.frame = CGRectMake(635,918,48,48);
        
    }
    
    [UIView commitAnimations];
    
    
    
    
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    UIBarButtonItem *closeButton = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAutomatic]
                                                                    style:UIBarButtonItemStylePlain
                                                                   target:self
                                                                   action:@selector( onBackClick:)];
    
    
    self.navigationItem.leftBarButtonItem = closeButton;
    
    self.imgview.image = self.img;
    
    
    UIApplication * app = [UIApplication sharedApplication];
    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
    //    [appDelegate didRotated];
    
    
    
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:animationDuration];
    
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication]statusBarOrientation];
    if (UIInterfaceOrientationIsLandscape(orientation))
    {
        
        
        self.buttonAlbum.frame = CGRectMake(942,120,48,48);
        self.buttonCamera.frame = CGRectMake(942,200,48,48);
        self.buttonUpload.frame = CGRectMake(942,363,48,48);
        //        @property (strong, nonatomic) IBOutlet UIButton *buttonAlbum;
        //        @property (strong, nonatomic) IBOutlet UIButton *buttonCamera;
        //        @property (strong, nonatomic) IBOutlet UIButton *buttonUpload;
    }
    else
    {
        self.buttonAlbum.frame = CGRectMake(82,918,48,48);
        self.buttonCamera.frame = CGRectMake(173,918,48,48);
        self.buttonUpload.frame = CGRectMake(635,918,48,48);
        
    }
    
    [UIView commitAnimations];
    
    // Do any additional setup after loading the view.
}
- (void)onBackClick:(UIButton *)sender {
    
    
    [self.navigationController popViewControllerAnimated:FALSE];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)onClickAlbum:(id)sender {
    
    NSUInteger sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    
    imagePickerController.delegate = self;
    
    imagePickerController.allowsEditing = YES;
    
    imagePickerController.sourceType = sourceType;
    
    [self presentViewController:imagePickerController animated:YES completion:^{}];
}
- (IBAction)onClickCamera:(id)sender {
    
    if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        return;
    }
    
    NSUInteger sourceType=UIImagePickerControllerSourceTypeCamera;
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    
    imagePickerController.delegate = self;
    
    imagePickerController.allowsEditing = YES;
    
    imagePickerController.sourceType = sourceType;
    
    [self presentViewController:imagePickerController animated:YES completion:^{}];
    
}
- (IBAction)onClickUpload:(id)sender {
    
    
    
    
    if(self.dirty==false)
    {
        
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Upload", nil) message:NSLocalizedString(@"Please set a photo first.", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"Ok", nil) otherButtonTitles:nil, nil];
        
        // alert.
        [alert show];
        return;
        
    }
    self.uploadProgress.progress = 0;
    
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    
    if(appDelegate.offline_mode)
    {
        
        NSData *data = [OLDataProvider offline_saveBusinesscard:UIImagePNGRepresentation(self.imgview.image)];;
        
        // 再将NSData转为字符串
        NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        
        //            NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        
        DebugLog(@"data string: %@",jsonStr);
        NSError *error=nil;
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
       
        
        
        if([[json valueForKey:@"result"] intValue]==2)
        {
            NSString* img_url_down = json[@"img_url_aname"];
            NSString* img_url_up = json[@"img_url"];
            
            if(self.returnValue)
                self.returnValue(img_url_down,img_url_up,self.imgview.image);
            
            [self.navigationController popViewControllerAnimated:false];
        }
        else
        {
            [RAUtils message_alert:[json valueForKey:@"err_msg"] title:@"Upload Image" controller:self] ;
        }
    }
    else
    {
        
        //    UIAlertView * waitalert = [[UIAlertView alloc] initWithTitle:@"wait" message:@"uploading" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
        //    [waitalert show];
        
        NSData *imageData = UIImagePNGRepresentation(self.imgview.image);
        
        AFHTTPRequestSerializer* serializer=[AFHTTPRequestSerializer serializer] ;
        
        
        
        NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
        
        if(appDelegate.user!=nil)
            [params setValue:appDelegate.user forKey:@"user"];
        //    if(appDelegate.contact_id!=nil)
        //        [params setValue:appDelegate.contact_id forKey:@"contactId"];
        if(appDelegate.password!=nil)
            [params setValue:appDelegate.password forKey:@"password"];
        
        
        NSMutableURLRequest *request = [serializer multipartFormRequestWithMethod:@"POST" URLString:URL_UPLOAD_IMG parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            [formData appendPartWithFileData:imageData name:@"upfile" fileName:@"test.jpg" mimeType:@"image/png"];
        } error:nil];
        
        
        //        NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:WEBSERVICE_URL parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        //            [formData appendPartWithFileData:imageData name:@"upfile" fileName:@"test" mimeType:@"image/png"];
        //        } error:nil];
        //
        AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        
        
        
        //manager.responseSerializer.acceptableContentTypes = [self.operationManager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
        
        
        
        //
        NSProgress *progress = nil;
        
        NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
            
            //        [progress removeObserver:self forKeyPath:@"fractionCompleted"];
            
            
            
            
            if (error) {
                
                NSString* err_msg = [error localizedDescription];
                DebugLog(@"%@",err_msg);// [self.view updateWithMessage:[NSString stringWithFormat:@"Error : %@!", error.debugDescription]];
                
                
                NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                
                DebugLog(@"data string: %@",str);
                [RAUtils message_alert:@"Can not connect to server please try again." title:@"Upload Image" controller:self] ;
                
            } else {
                DebugLog(@"response ");
                
                
                
                NSData *data = [NSJSONSerialization dataWithJSONObject:(NSDictionary*)responseObject options:kNilOptions error:nil];
                
                // 再将NSData转为字符串
                NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                
                //            NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                
                DebugLog(@"data string: %@",jsonStr);
                
                NSDictionary* json = responseObject;
                
                
                if([[json valueForKey:@"result"] intValue]==2)
                {
                    NSString* img_url_down = json[@"img_url_aname"];
                    NSString* img_url_up = json[@"img_url"];
                    
                    if(self.returnValue)
                        self.returnValue(img_url_down,img_url_up,self.imgview.image);
                    
                    [self.navigationController popViewControllerAnimated:false];
                }
                else
                {
                    [RAUtils message_alert:[json valueForKey:@"err_msg"] title:@"Upload Image" controller:self] ;
                }
                
                
            }
            //  [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
        }];
        
        
        
        
        [self.uploadProgress setProgressWithUploadProgressOfTask:uploadTask animated:true];
        //
        
        
        
        
        
        
        [uploadTask resume];
        
    }
}


#pragma mark - imagePicker delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    self.dirty = true;
    /*-------------------------------相机拍照--------------------------------------*/
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        
        UIImage * image = [info objectForKey:UIImagePickerControllerEditedImage];
        
        image=[RAUtils img_compress:image kbsize:500];
        self.imgview.image = image;
        [picker dismissViewControllerAnimated:YES completion:^{
        }];
        
    } else if (picker .sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
        
        /**
         *  UIImagePickerControllerEditedImage 取得的是被编辑过的图片,需要allowsEditing设置为YES
         *  UIImagePickerControllerOriginalImage 取得的是相册中原始图片
         */
        UIImage * image = [info objectForKey:UIImagePickerControllerEditedImage];
        
        image=[RAUtils img_compress:image kbsize:500];
        self.imgview.image = image;
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
    
    
}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    //      [picker presentViewController:cameraPicker animated:YES completion:nil];
    DebugLog(@"%s",__FUNCTION__);
}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
