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

import Foundation
import Pachyderm

@MainActor
class UpdateFilterService {
    private let filter: EditedFilter
    private let mastodonController: MastodonController
    
    init(filter: EditedFilter, mastodonController: MastodonController) {
        self.filter = filter
        self.mastodonController = mastodonController
    }

    func run() async throws {
        let context = mastodonController.persistentContainer.viewContext
        let mo = try context.fetch(FilterMO.fetchRequest(id: filter.id!)).first!
        
        let updateFrom: AnyFilter
        if mastodonController.instanceFeatures.filtersV2 {
            var updates = filter.keywords.map {
                if let id = $0.id {
                    return FilterV2.KeywordUpdate.update(id: id, keyword: $0.keyword, wholeWord: $0.wholeWord)
                } else {
                    return FilterV2.KeywordUpdate.add(keyword: $0.keyword, wholeWord: $0.wholeWord)
                }
            }
            for existing in mo.keywordMOs where !filter.keywords.contains(where: {  existing.id == $0.id }) {
                if let id = existing.id {
                    updates.append(.destroy(id: id))
                }
            }
            let req = FilterV2.update(filter.id!, title: filter.title ?? "", context: filter.contexts, expiresIn: filter.expiresIn, action: filter.action, keywords: updates)
            let (updated, _) = try await mastodonController.run(req)
            updateFrom = .v2(updated)
        } else {
            let req = FilterV1.update(filter.id!, phrase: filter.keywords.first!.keyword, context: filter.contexts, irreversible: false, wholeWord: filter.keywords.first!.wholeWord, expiresIn: filter.expiresIn)
            let (updated, _) = try await mastodonController.run(req)
            updateFrom = .v1(updated)
        }
        
        mo.updateFrom(apiFilter: updateFrom, context: context)
        mastodonController.persistentContainer.save(context: context)
    }
}
