//
//  EmailFilterModel.swift
//  PhoneManager
//
//  Created by edy on 2025/5/9.
//

import UIKit

class EmailFilterManager: NSObject {

    static let share = EmailFilterManager()
    
    var SelectEmailSet:[NSMutableSet] = (0..<5).map { _ in NSMutableSet() }
    var FilterSet:EmailFilterData {
        get {
            return self.getFilterSet()
        }
        set{
            guard var path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
            path = path.appendingPathComponent("EmailFilter.json")
            do{
                let data = try JSONEncoder().encode(newValue)
                try data.write(to: path)
            }catch{
            }
        }
    }
    
    
    
    func signOut() -> Void {
        keyword = []
        guard let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
        let path1 = path.appendingPathComponent("EmailFilter.json")
        do{
            try FileManager.default.removeItem(at: path1)
        }catch{ }
    }
    
    var keyword:[String] {
        set {
            guard let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
            let path2 = path.appendingPathComponent("keyword.json")
            do{
                let data = try JSONEncoder().encode(newValue)
                try data.write(to: path2)
            }catch{}
        }
        get {
            guard let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return [] }
            let path2 = path.appendingPathComponent("keyword.json")
            do {
                let dataFile = try Data(contentsOf: path2)
                let decode = try JSONDecoder().decode([String].self, from:dataFile)
                return decode
            }catch{
                return []
            }
        }
    }
    
    func getFilterSet() -> EmailFilterData {
        guard let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return EmailFilterData() }
        let path1 = path.appendingPathComponent("EmailFilter.json")
        do {
            let dataFile = try Data(contentsOf: path1)
            let decode = try JSONDecoder().decode(EmailFilterData.self, from:dataFile)
            return decode
        }catch{
            return EmailFilterData()
        }
    }
    
    func EmailfilterHeaders() -> [EmailFilterModel] {
        let data = [ ["header":"TIME","child":[ ["title":"Delete all mails from selected categories"],
                                                ["title":"Delete 1 week and older mails"],
                                                ["title":"Delete 1 month and older mails"],
                                                ["title":"Delete 1 year and older mails"] ]
                     ],
                     ["header":"FAVORITE","child":[ ["title":"Delete stared mails" ] ]
                                  ],
                     ["header":"READ & UNREAD","child":[ ["title":"Delete read mails"],
                                                       ["title":"Delete unread mails"] ]
                                  ],
                     ["header":"KEYWORDS","child":[ ["title":"Do not delete mails that contains the keywords below" ] ]
                                  ]
        ]
        do{
            let encode = try JSONSerialization.data(withJSONObject: data)
            let decode = try JSONDecoder().decode([EmailFilterModel].self, from: encode)
            return decode
        }catch{
            return []
        }
    }
    
}

struct EmailFilterModel: Codable {
    var header:String?
    var child:[EmailFilterChildModel]?
}

struct EmailFilterChildModel:Codable {
    var title:String?
}

struct EmailFilterData:Codable {
    var date:Int = 0
    var start:Bool = false
    var read:Bool = true
    var unread:Bool = false
    var keyword:Bool = false
}


func PmEmailData() -> [EmailDetailModel] {
    let data = [["label":"Social Media","child":[] ],
                ["label":"Promotions","child":[] ],
                ["label":"Updates","child":[] ],
                ["label":"Forum","child":[] ],
                ["label":"Spam","child":[] ] ]
    do{
        let d = try JSONSerialization.data(withJSONObject: data)
        let ret = try JSONDecoder().decode([EmailDetailModel].self, from: d)
        return ret
    }catch{
        return []
    }
}

struct EmailDetailModel : Codable {
    var label:String = ""
    var child:[EmailMessageModel] = []
}

struct EmailMessageModel:Codable {
    var messageId:String?               // 消息id
    var labelids:[String]?              // 标签
    var snippet:String?                 //
    var payload:EmailMessagepayLoadModel?
}

struct EmailMessagepayLoadModel : Codable {
    var body:EmailMessageBodyModel = EmailMessageBodyModel()
    var headers:EmailMessageHeadersModel?
}

struct EmailMessageBodyModel:Codable {
    var plainText:String?       // 内容 text
    var html:String?            // 内容 html
}

struct EmailMessageHeadersModel : Codable {
    var from:String?            // 发件人
    var subject:String?         // 主题
    var date:String?            // 时间
    var to:String?              // 收件人
}


extension String {
    
    func date(_ format:String) -> Date {
        let dateformatter = DateFormatter()
        dateformatter.calendar = Calendar(identifier: .gregorian)
        dateformatter.dateFormat = format
        return dateformatter.date(from: self) ?? Date()
    }
    
    func GetddMM() -> String {
        return self.EmailDateFromat().string("dd MMM yyyy")
    }
        
    func EmailDateFromat() -> Date {
        return self.date("EEE, dd MMM yyyy HH:mm:ss zzz")
    }
    
}

