//
//  EditedFilter.swift
//  Tusker
//
//  Created by Shadowfacts on 12/2/22.
//  Copyright © 2022 Shadowfacts. All rights reserved.
//

import Foundation
import Pachyderm

class EditedFilter: ObservableObject {
    static let defaultExpiresInForExpired: TimeInterval = 24 * 60 * 60
    
    let id: String?
    @Published var title: String?
    @Published var contexts: [FilterV1.Context]
    @Published var expiresIn: TimeInterval?
    @Published var keywords: [Keyword]
    @Published var action: FilterV2.Action
    
    init() {
        self.id = nil
        self.title = nil
        self.contexts = [.home]
        self.expiresIn = nil
        self.keywords = [.init(id: nil, keyword: "", wholeWord: true)]
        self.action = .warn
    }
    
    init(_ mo: FilterMO) {
        self.id = mo.id
        self.title = mo.title
        self.contexts = mo.contexts
        if let expiresAt = mo.expiresAt {
            if expiresAt <= Date() {
                expiresIn = EditedFilter.defaultExpiresInForExpired
            } else {
                expiresIn = expiresAt.timeIntervalSinceNow
            }
        }
        self.keywords = mo.keywordMOs.map {
            Keyword(id: $0.id, keyword: $0.keyword, wholeWord: $0.wholeWord)
        }
        self.action = mo.filterAction
    }
    
    init(copying other: EditedFilter) {
        self.id = other.id
        self.title = other.title
        self.contexts = other.contexts
        self.expiresIn = other.expiresIn
        self.keywords = other.keywords
        self.action = other.action
    }
    
    func isValid(for mastodonController: MastodonController) -> Bool {
        if mastodonController.instanceFeatures.filtersV2 && (title == nil || title!.isEmpty) {
            return false
        }
        if keywords.isEmpty || keywords.contains(where: { $0.keyword.isEmpty }) {
            return false
        }
        if contexts.isEmpty {
            return false
        }
        return true
    }
    
    struct Keyword {
        let id: String?
        var keyword: String
        var wholeWord: Bool
    }
}
