
//
//  PQSourcesFileUtil.swift
//  PQSpeed
//
//  Created by SanW on 2020/7/23.
//  Copyright © 2020 BytesFlow. All rights reserved.
//

import BFCommonKit
import UIKit

public class PQSingletoSourcesFileUtil: NSObject {
    public static let shared = PQSingletoSourcesFileUtil()

    public let cPlistPath = NSString(string: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!).appendingPathComponent("sourcesFile.plist")

    public func createFile() -> Bool {
        let fm = FileManager.default
        if fm.fileExists(atPath: cPlistPath) {
            return true
        }
        return fm.createFile(atPath: cPlistPath, contents: nil, attributes: nil)
    }

    public func writeFile(isString: Bool, key: String, sourceNmae: String) -> Bool {
        // 获取加密文件路径
        var object: String?
        if isString {
            object = DES3Util.encryptUseDES(sourceNmae, key: key)
        } else {
            guard let imDataPath = Bundle.main.path(forResource: sourceNmae, ofType: "png") else { return false }
            let imageData = NSData(contentsOfFile: imDataPath)
            object = DES3Util.encryptUseDES(imageData?.base64EncodedString(options: .lineLength64Characters), key: key)
        }
        if object != nil, (object?.count ?? 0) > 0 {
            let oldData: NSDictionary = NSMutableDictionary(contentsOfFile: cPlistPath) ?? NSMutableDictionary()
            oldData.setValue(object, forKey: key.md5)
            let success: Bool = oldData.write(toFile: cPlistPath, atomically: true)
            if success {
                BFLog(message: "写入成功:\(oldData)")
            } else {
                BFLog(message: "写入失败:\(oldData)")
            }
            return success
        }
        return false
    }

    public func readFile(isString: Bool, key: String) -> Any {
        let oldData = NSDictionary(contentsOfFile: Bundle.main.path(forResource: "sourcesFile.plist", ofType: nil) ?? "")
        BFLog(message: "oldData = \(oldData),key = \(key.md5)")
        let enStr = oldData?.object(forKey: key.md5)
        let desStr = DES3Util.decryptUseDES(enStr as? String, key: key)
        BFLog(message: "读取成功:\(desStr)")
        if isString {
            return desStr ?? ""
        } else {
            let data = NSData(base64Encoded: desStr ?? "", options: .ignoreUnknownCharacters)
            return UIImage(data: data! as Data) ?? ""
        }
    }

    override public init() {
        super.init()
    }

    override public func copy() -> Any {
        return self
    }

    override public func mutableCopy() -> Any {
        return self
    }
}
