//
//  ReportSelectRulesView.swift
//  Tusker
//
//  Created by Shadowfacts on 1/13/23.
//  Copyright © 2023 Shadowfacts. All rights reserved.
//

import SwiftUI

struct ReportSelectRulesView: View {
    @ObservedObject var mastodonController: MastodonController
    @ObservedObject var report: EditedReport
    
    var selectedRuleIDs: [String] {
        get {
            if case .rules(let ids) = report.reason {
                return ids
            } else {
                return []
            }
        }
        nonmutating set {
            report.reason = .rules(newValue)
        }
    }
    
    init(mastodonController: MastodonController, report: EditedReport) {
        self.mastodonController = mastodonController
        self.report = report
    }
    
    var body: some View {
        List(mastodonController.instance!.rules!) { rule in
            Button {
                if selectedRuleIDs.contains(rule.id) {
                    selectedRuleIDs.removeAll(where: { $0 == rule.id })
                } else {
                    selectedRuleIDs.append(rule.id)
                }
            } label: {
                HStack {
                    Text(rule.text)
                        .foregroundColor(.primary)
                    Spacer()
                    Image(systemName: "checkmark")
                        .foregroundColor(selectedRuleIDs.contains(rule.id) ? .accentColor : .clear)
                }
            }
            .appGroupedListRowBackground()
        }
        .withAppBackgroundIfAvailable()
        .navigationTitle("Rules")
    }
}

private extension View {
    @available(iOS, obsoleted: 16.0)
    @ViewBuilder
    func withAppBackgroundIfAvailable() -> some View {
        if #available(iOS 16.0, *) {
            self
                .scrollContentBackground(.hidden)
                .background(Color.appGroupedBackground)
        } else {
            self
        }
    }
}

//struct ReportSelectRulesView_Previews: PreviewProvider {
//    static var previews: some View {
//        ReportSelectRulesView()
//    }
//}
