import Flutter
import UIKit


struct PersistentLoggerConstants{
    static let LOGGER_ID = "logger_id"
    static let LOG_NAME = "log_name"
    static let FILE_SIZE_LIMIT = "file_size"
    static let FILE_COUNT = "file_count"
    static let LEVEL = "level"
    static let FORMATTER = "formatter"
    static let FILE_ROLL_TIME = "file_roll_time"
    static let ECHO = "echo"
    static let MESSAGE = "msg"
}

enum Formatter:Int {
    case MAIN = 0
    case RAW = 1
}
public class SwiftPersistentPlugin: NSObject, FlutterPlugin {
    public static func register(with registrar: FlutterPluginRegistrar) {
        let channel = FlutterMethodChannel(name: "app.guru.persistent.LOG", binaryMessenger: registrar.messenger())
        let instance = SwiftPersistentPlugin()
        registrar.addMethodCallDelegate(instance, channel: channel)
    }
    
    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
//        result("iOS " + UIDevice.current.systemVersion)
//        PersistentPlugin.isEqual(self)
        
        
        let arguments = call.arguments as? [String: Any] ?? [String: Any]()
        
        switch call.method {
            
        case "create_log":
            createLogger(arguments: arguments, result: result)
            break
        case "clear_log":
            clearLogger(arguments: arguments,result:result)
            break
        case "log":
            logMessage(arguments: arguments,result:result)
            break
        case "get_log_root_dir":
            getLogRootDir(arguments: arguments,result:result)
            break
        default:
            result(FlutterMethodNotImplemented)
        }
       
    }
    
    private func createLogger(arguments: [String: Any], result: @escaping FlutterResult) {
        let logName =
        arguments[PersistentLoggerConstants.LOG_NAME] as? String
        let fileSizeLimit =
        arguments[PersistentLoggerConstants.FILE_SIZE_LIMIT] as? UInt64
        let fileRollTime = arguments[PersistentLoggerConstants.FILE_ROLL_TIME] as? TimeInterval
        let fileCount =
        arguments[PersistentLoggerConstants.FILE_COUNT] as? UInt
        let echo =
        arguments[PersistentLoggerConstants.ECHO] as? Bool ?? false
        
        let formatter = arguments[PersistentLoggerConstants.FORMATTER] as? Int ?? Formatter.MAIN.rawValue
        guard let fillName = logName else {
           result(false)
            return
        }
      
        let fileManager:DDLogFileManagerDefault = DDLogFileManagerDefault(logsDirectory: fillName)
        let format:DDLogFileFormatterDefault? = formatter == Formatter.MAIN.rawValue ? DDLogFileFormatterDefault():nil
        let fileLogger: DDFileLogger = DDFileLogger(logFileManager: fileManager, logfileFormatter:format)
       
        if let fileSize = fileSizeLimit {
            fileLogger.maximumFileSize = fileSize
        }
        
        if let fileRoll = fileRollTime {
            fileLogger.rollingFrequency = TimeInterval(fileRoll)
        }
        
        if let fileCount = fileCount{
            fileLogger.logFileManager.maximumNumberOfLogFiles = fileCount
        }
        
        if(echo){
            fileLogger.canEchoMessage = true
        }
        
    
//        fileLogger.rollingFrequency = 60 * 60 * 24 // 24 hours
        print(fileManager.logsDirectory)
        DDLog.add(fileLogger)
        result(true)
    }
    
    private func clearLogger(arguments: [String: Any], result: @escaping FlutterResult) {
        let logName =
        arguments[PersistentLoggerConstants.LOG_NAME] as? String
        guard let logName = logName else {
            result(false)
            return
        }
      
      let remove =  DDLog.removeFile(withName: logName)
        result(remove)
        
    }
    
    private func logMessage(arguments: [String: Any], result: @escaping FlutterResult) {
        let logName =
        arguments[PersistentLoggerConstants.LOG_NAME] as? String
        let logMessage = arguments[PersistentLoggerConstants.MESSAGE] as? String
        
        guard let logName = logName,let logMessage = logMessage else {
            result(false)
            return
        }
        
        if(DDLog.getDirectoryWithFile(logName) == false){
            result(false)
            return
        }
        
        GuruLogDebug(targetFile: logName, logMessage)
        result(true)
        
    }
    private func getLogRootDir(arguments: [String: Any], result: @escaping FlutterResult){
        let rootPath = DDLog.rootLogsDirectory()
        result(rootPath)
        
    }
}
