//
//  SyncControlPanelViewController.m
//  iSales-NPD
//
//  Created by Ray on 7/8/16.
//  Copyright © 2016 United Software Applications, Inc. All rights reserved.
//

#import "SyncControlPanelViewController.h"
#import "AppDelegate.h"
#import "RAUtils.h"
@interface SyncControlPanelViewController ()

@end

@implementation SyncControlPanelViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone ;
    
    self.closeButton = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"close"] imageWithRenderingMode:UIImageRenderingModeAutomatic]
                                                                    style:UIBarButtonItemStylePlain
                                                                   target:self
                                                                   action:@selector( onCloseClick:)];
    
    self.closeButton.enabled=false;
    self.navigationItem.rightBarButtonItem = self.closeButton;
    
    
    self.tv_log.layer.borderWidth=1 ; //边框粗细
    self.tv_log.layer.borderColor=[UIColor darkGrayColor].CGColor; //边框颜色
    
    
                    UIApplication * app = [UIApplication sharedApplication];
                    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
    appDelegate.settingUI=self;

    // Do any additional setup after loading the view.
}
- (void)onCloseClick:(UIButton *)sender {
    
    //    if(self.onDismissVC)
    //        self.onDismissVC();
    [self dismissViewControllerAnimated:true completion:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void) onProgressUpdate
{
    
    UIApplication * app = [UIApplication sharedApplication];
    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
    
    self.progress_overall.progress= appDelegate.overall_progress;
    self.progress_current.progress= appDelegate.file_progress;
    
    
}
- (IBAction)onSendlogClick:(id)sender {
    UIApplication * app = [UIApplication sharedApplication];
    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
    
    
    if(appDelegate.downloadlog.length==0)
    {
        [RAUtils message_alert:@"Log is empty sending canceled." title:@"Sending log" controller:self] ;
        return;
    }
    
    
    
    //  NSString *path = NSTemporaryDirectory();
    
    //    CFUUIDRef uuidObject = CFUUIDCreate(kCFAllocatorDefault);
    
    // Get the string representation of CFUUID object.
    
    NSString* filename =[[NSUUID UUID] UUIDString];
    //  NSString *filePath = [path stringByAppendingPathComponent:filename];
    
    
    
    
    
    MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
    
    if(mc==nil)
        return;
    mc.mailComposeDelegate = self;
    [mc setSubject:@"offline sync log"];
    
    
    [mc setToRecipients:@[@"ray.zhang@united-cn.net",@"RedAntSupport@united-us.net"]];
    
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // CFShow(infoDictionary);
    // app名称
    NSString *app_Name = [infoDictionary objectForKey:@"CFBundleName"];
    // app版本
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    // app build版本
    NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
    
    
    NSString* appinfo =[NSString stringWithFormat:@"App info: %@   %@ build%@</br>",app_Name,app_Version,app_build];
    
    NSString* userinfo =[NSString stringWithFormat:@"login info: %@  </br>",appDelegate.user];
    //    if(self.mail_content==nil)
    //        self.mail_content=@"";
    
    NSString* htmlbody = [NSString stringWithFormat:@"<p>%@</p></br>%@%@</br></br>%@",@"Process description:",appinfo,userinfo,[appDelegate.downloadlog stringByReplacingOccurrencesOfString:@"\n" withString:@"</br>"]];
    
    [mc setMessageBody:htmlbody
                isHTML:YES];
    
    
    
    NSData *data = [appDelegate.downloadlog dataUsingEncoding:NSUTF8StringEncoding];//[NSData dataWithContentsOfFile:filePath];
    
    //    if(self.attachment_name.length>0)
    //        filename = self.attachment_name;
    
    NSString* dbzippath= [RAUtils getdbzip];
    NSData *data1 = [NSData dataWithContentsOfFile:dbzippath];
//    filename=@"database.db";
    
    
    
//    [mc addAttachmentData:data mimeType:@"text/plain" fileName:filename];
    [mc addAttachmentData:data1 mimeType:@"application/zip" fileName:@"db.zip"];
    
    [self presentModalViewController:mc animated:YES];
    
    return;
    
}

-(void) onLogUpdate
{
    UIApplication * app = [UIApplication sharedApplication];
    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        self.tv_log.text = appDelegate.downloadlog;
        
        [self.tv_log scrollRangeToVisible:NSMakeRange(appDelegate.downloadlog.length-1,0)];
    });
    
    
}

-(void) onSyncFinish
{
    self.closeButton.enabled=true;
//    UIApplication * app = [UIApplication sharedApplication];
//    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
//    appDelegate.downloadlog=nil;
//    appDelegate.downloading=false;
////    self.downloadlog=nil;
////    self.downloading=false;
//    appDelegate.download_task=nil;
//    appDelegate.vid=nil;
}
/*
#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.
}
*/
- (void)mailComposeController:(MFMailComposeViewController*)controller
          didFinishWithResult:(MFMailComposeResult)result
                        error:(NSError*)error {
    switch (result)
    {
        case MFMailComposeResultCancelled:
            DebugLog(@"Mail send canceled...");
            break;
        case MFMailComposeResultSaved:
            DebugLog(@"Mail saved...");
            break;
        case MFMailComposeResultSent:
            DebugLog(@"Mail sent...");
            break;
        case MFMailComposeResultFailed:
            DebugLog(@"Mail send errored: %@...", [error localizedDescription]);
            break;
        default:
            break;
    }
    [self dismissModalViewControllerAnimated:YES];
}
@end
