//
//  FilterRow.swift
//  Tusker
//
//  Created by Shadowfacts on 11/30/22.
//  Copyright © 2022 Shadowfacts. All rights reserved.
//

import SwiftUI
import Pachyderm

struct FilterRow: View {
    @ObservedObject var filter: FilterMO
    @EnvironmentObject var mastodonController: MastodonController
    
    var body: some View {
        VStack(alignment: .leading) {
            HStack(alignment: .top) {
                Text(mastodonController.instanceFeatures.filtersV2 ? filter.title ?? "" : filter.keywordMOs.first?.keyword ?? "")
                    .font(.headline)
                
                Spacer()
                
                if let expiresAt = filter.expiresAt {
                    if expiresAt <= Date() {
                        Text("Expired")
                            .font(.body.lowercaseSmallCaps())
                            .foregroundColor(.red)
                    } else {
                        Text(expiresAt.formatted(.relative(presentation: .numeric, unitsStyle: .narrow)))
                            .font(.body.lowercaseSmallCaps())
                    }
                }
            }
            
            if mastodonController.instanceFeatures.filtersV2 {
                Text("^[\(filter.keywords.count) keywords](inflect: true)")
            }
            
            // rather than mapping over filter.contexts, because we want a consistent order
            Text(FilterV1.Context.allCases.filter { filter.contexts.contains($0) }.map(\.displayName).formatted())
                .font(.subheadline)
            
            if !mastodonController.instanceFeatures.filtersV2 && filter.keywordMOs.first?.wholeWord == true {
                Text("Whole word")
                    .font(.subheadline)
                    .foregroundColor(.secondary)
            }
        }
    }
}

struct FilterRow_Previews: PreviewProvider {
    static var previews: some View {
        let filter = FilterMO()
        filter.id = "1"
//        filter.phrase = "test"
        filter.expiresAt = Date().addingTimeInterval(60 * 60)
//        filter.wholeWord = true
        filter.contexts = [.home]
        return FilterRow(filter: filter)
    }
}
