//
//  DownLoaderFile.swift
//  MobilePortal
//
//  Created by caiyang on 2021/2/8.
//  Copyright © 2021 yin chen. All rights reserved.
//

import UIKit

private let kCachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first

@objcMembers class DownLoaderFile: NSObject {
    fileprivate var path : String?
//    fileprivate var connection : NSURLConnection?
//    fileprivate var fileHandle : FileHandle?
    fileprivate var outputStream: OutputStream?
    fileprivate var gotoblock: passParameterBlock?
    fileprivate var errorBlock: selectBlock?
    var downLoaderUrlStr:String?
//    fileprivate var tmpSize : CLongLong = 0
//    fileprivate var totalSize : CLongLong = 0
    
    
    class func sharedInstance()->DownLoaderFile {
        struct SharedStatic {
            static var instance: DownLoaderFile = DownLoaderFile()
        }
        return SharedStatic.instance
    }
    
    fileprivate lazy var session : URLSession  = {
        let config = URLSessionConfiguration.default
        let session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue.main)
        return session
    }()
    /// 获取问号前的链接
    public func getWebUrl(urlStr:String?) -> String {
        if (urlStr?.contains("?"))! {
            let string = urlStr! as NSString
            let startRange = string.range(of: "?")
            let range = NSMakeRange(0, startRange.location)
            let result = string.substring(with: range)
            return result
        }
        return urlStr!
    }
    func downloaderFileAction(downLoaderUrl:String!,cookie:String? ,gotoblock:@escaping passParameterBlock,errorBlock:@escaping selectBlock)  {
        downLoaderUrlStr = downLoaderUrl
        self.gotoblock = gotoblock
        self.errorBlock = errorBlock
        self.path = ""
        if (downLoaderUrl?.contains("?"))! && downLoaderUrl.contains("download.do") {
            let dic:NSMutableDictionary = (WebActionOC.share()?.getURLParameters(downLoaderUrl!))!
            let filename:String = dic.object(forKey: "filename")! as! String
            self.path = kCachePath!  + "/" + filename
            let parameters:String = (WebActionOC.share()?.getDictStr(dic))!
//            print(parameters)
            downLoaderUrlStr = self.getWebUrl(urlStr: downLoaderUrl) + "?" + parameters
            print(downLoaderUrlStr!)
        }
        let url:NSURL = NSURL.init(string: WebActionOC.share().getUrl(downLoaderUrlStr))!
        guard url.lastPathComponent != nil else {
            print("url有问题")
            SMToastView.showMessage("文件地址有误！")
            return
        }
        var urlRequest = NSURLRequest(url: url as URL, cachePolicy: NSURLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 5) as URLRequest
        urlRequest.setValue(cookie, forHTTPHeaderField: "Cookie")
//        urlRequest.setValue("gzip,deflate", forHTTPHeaderField: "Accept-Encoding")
//        urlRequest.setValue("bytes=0-", forHTTPHeaderField: "Range")
//        urlRequest.setValue("text/plain", forHTTPHeaderField: "Content-Type")
        let dataTask = self.session.dataTask(with: urlRequest)
//        let dataTask = self.session.dataTask(with: urlRequest) { (data, response, error) in
//            print(data!)
//            print(response!)
////            print(error!)
//        }
        dataTask.resume()
    }
    
    deinit {
        print("------------------------------")
        print(NSStringFromClass(self.classForCoder)+"释放")
        print("------------------------------")
    }
    func removeFile(sourceUrl:String){
        let fileManger = FileManager.default
        do{
            try fileManger.removeItem(atPath: sourceUrl)
            print("Success to remove file.")
        }catch{
            print("Failed to remove file.")
        }
    }
}
extension DownLoaderFile : URLSessionDataDelegate {
    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Swift.Void){
        let resp:HTTPURLResponse = response as! HTTPURLResponse
        print("response status code:",resp.statusCode)
        print("response expect length:",resp.expectedContentLength)
        print("response all headfield:",resp.allHeaderFields)
        if resp.statusCode != 200  {
            SMToastView.showMessage(String(resp.statusCode))
            self.errorBlock!()
            return
        }
        if self.path?.count == 0 {
            let suggestedFilename = WebActionOC.share()?.decodingAction(response.suggestedFilename)
            self.path = kCachePath! + "/" + suggestedFilename!
        }
        print(path!)
        //检查当前路径是否已经下载了该文件
        if FileTool.fileExists(filePath: path!) {
            print("删除已有文件")
            FileTool.removeFile(self.path!)
//            self.gotoVCBlock()
        }
        let manager:FileManager = FileManager.default
        if !manager.fileExists(atPath: path!) {
            manager.createFile(atPath: path!, contents: nil, attributes: nil)
        }
        self.outputStream = OutputStream(toFileAtPath: path!, append: true)
        self.outputStream?.open()
        completionHandler(URLSession.ResponseDisposition.allow);
    }
    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
//        self.fileHandle?.seekToEndOfFile()
//        self.fileHandle?.write(data)
        var buffer = [UInt8](repeating: 0, count: data.count)
        data.copyBytes(to: &buffer, count: data.count)
        self.outputStream?.write(buffer, maxLength: data.count)
    }
    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?){
        print("请求完成")
        if (error == nil) {
            self.gotoblock!(self.path!)
        }else {
            print(error!)
            SMToastView.showMessage(judgmentStrNil(str: error!.localizedDescription))
            self.errorBlock!()
        }
        self.outputStream?.close()
    }
}
