
#import "msg.h"
#import "macro.h"
#import "version.h"
#import "constants.h"
#import "DaemonUpdate.h"


// 我的更新
@interface DaemonUpdate()<NSURLSessionDownloadDelegate> {
	
	int _updateTicker;
	int _clientVersion;
	int _serverVersion;
	//NSString * _downloadUrl;
	BOOL _isDownLoadDeb;

	BOOL _isDownLoadFinish;
	NSString * _downloadPath;
}

@end

@implementation DaemonUpdate


+ (instancetype) shareInstance {
    static DaemonUpdate *_instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[DaemonUpdate alloc] init];
    });
    return _instance;
}

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

- (void)_init {

	_updateTicker = 0;

	// 我的更新
	_clientVersion = 1000;
	_serverVersion = 0;
	self.downloadUrl = @"";
	_isDownLoadDeb = NO;
	_isDownLoadFinish = NO;
}

// 检查更新
- (BOOL)checkVersion {

	if(_clientVersion < _serverVersion) {
		if(_isDownLoadDeb == NO){
			[self downloadDeb];
		}
		if(_isDownLoadFinish == YES) {
			_isDownLoadFinish = NO;
			[self installDeb];
		}
		return YES;
	} else {
		[self getVersion];
	}
	return NO;
}

- (BOOL) zeroVersion {
	_clientVersion = 0;
	return YES;
}

- (BOOL) getVersion {
	//dispatch_semaphore_t sem = dispatch_semaphore_create(0);
	// CSLog(@"··········  获取服务器Deb的版本信息 ··········");

	NSString *param 	= [NSString stringWithFormat:@"ver=%d&name=%@", _clientVersion,[[UIDevice currentDevice] name]];
    NSString *url 		= [NSString stringWithFormat:@"http://%@/version?%@", TASK_SERVER_HOST, [param stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
	NSURL *taskURL = [NSURL URLWithString: url];
    NSMutableURLRequest *taskReq = [NSMutableURLRequest requestWithURL:taskURL];
    NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:taskReq completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error){
			CSLog(@"*** 更新网络请求错误 ***");
            // CSLog(@"### Deb更新错误请求 %@ with code %ld ###", taskURL.absoluteString, (long)[(NSHTTPURLResponse *)response statusCode]);
            //dispatch_semaphore_signal(sem);
            return;
        }
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        if (dict == nil){
            CSLog(@"*** 更新转化Json错误 ***");
            //dispatch_semaphore_signal(sem);
            return;
        }
        NSInteger code = [dict[@"ret"] integerValue];
        if (code == 0 ){

			NSDictionary *updateInfo = dict[@"data"];
			NSInteger version = [updateInfo[@"version"] integerValue];
			NSString* fullUrl = updateInfo[@"fullUrl"];
			// CSLog(@"·········· 更新: %@, ··········", updateInfo);
			// CSLog(@"·········· 更新版本: %ld, ··········", version);
			// CSLog(@"·········· 更新地址: %@, ··········", fullUrl);
			_serverVersion = version;
			self.downloadUrl = [NSString stringWithFormat:@"%@",fullUrl];

        }else{
           CSLog(@"·········· 失败: %@, ··········", dict);
        }
        //dispatch_semaphore_signal(sem);
    }];
    [task resume];
	return NO;
}

// 下载资源
- (BOOL)downloadDeb {

	CSLog(@"··········  正在下载资源:%@ ··········",self.downloadUrl);
	_isDownLoadDeb = YES;

  	//1.url
  	NSURL *url = [NSURL URLWithString: self.downloadUrl];
  	//2.创建请求对象
  	NSURLRequest *request = [NSURLRequest requestWithURL:url];
  	//3.创建session
  	NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
  	self.session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
  	//4.创建Task
  	NSURLSessionDownloadTask *downloadTask = [self.session downloadTaskWithRequest:request];
  	//5.执行Task
  	[downloadTask resume];
	return NO;
}

// 安装deb
- (BOOL)installDeb {
	
	CSLog(@"·········· 安装Deb: %@, ··········", self.downloadPath);
	//NSString* doSystemCmd = [NSString stringWithFormat:@"dpkg -i %@",self.downloadPath];
	NSString* doSystemCmd = [NSString stringWithFormat:@"mv %@ /private/var/mobile/Media/update.deb",self.downloadPath];
	
	CSLog(@"·········· %@, 1··········", doSystemCmd);
	system([doSystemCmd UTF8String]);
	// system("nohup /usr/bin/dpkg -i /var/mobile/Media/update.deb &");
	// system("dpkg -i /private/var/mobile/Media/update.deb");
	// system("/var/mobile/Media/update.sh");
	CSLog(@"·········· %@, 2··········", doSystemCmd);

// GCD_AFTER_MAIN(5)
// 	CSLog(@"·········· %@, 2··········", doSystemCmd);
// 	system("/usr/bin/dpkg -i /private/var/mobile/Media/update.deb");
// 	// dispatch_async(dispatch_get_main_queue(), ^{
// 	// 	system("dpkg -i /private/var/mobile/Media/update.deb");
// 	// });
// GCD_END
	return NO;
}


#pragma mark ----------------------
#pragma mark NSURLSessionDownloadDelegate
/**
 * 写数据
 *
 * @param session          会话对象
 * @param downloadTask       下载任务
 * @param bytesWritten       本次写入的数据大小
 * @param totalBytesWritten     下载的数据总大小
 * @param totalBytesExpectedToWrite 文件的总大小
 */
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
	//1. 获得文件的下载进度
	CSLog(@"***********************<%f>***********************",1.0 * totalBytesWritten/totalBytesExpectedToWrite);
}
 
/**
 * 当恢复下载的时候调用该方法
 *
 * @param fileOffset     从什么地方下载
 * @param expectedTotalBytes 文件的总大小
 */
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
{
	CSLog(@"**********************************************");
	CSLog(@"%s",__func__);
}
 
/**
 * 当下载完成的时候调用
 *
 * @param location   文件的临时存储路径
 */
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
	CSLog(@"**********************************************");
 	//CSLog(@"当下载完成的时候调用 : %@",location);
   
 	//1 拼接文件全路径
  	NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
   	CSLog(@"当下载完成的时候调用 : %@",fullPath);

  	//2 剪切文件
  	[[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:fullPath] error:nil];
  	//CSLog(@"%@",fullPath);
	
	self.downloadPath = [NSString stringWithFormat:@"%@",fullPath];
	_isDownLoadFinish = YES;
}
 
/**
 * 请求结束
 */
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
	CSLog(@"**********************************************");
	CSLog(@"didCompleteWithError");
}




@end
