//
//  SmallHeaderView.swift
//  Feels (iOS)
//
//  Created by Trey Tartt on 1/28/22.
//

import SwiftUI

struct SmallRollUpHeaderView: View {
    var entries = [(Mood, Int)]()
    let backDays: Int
    
    init(fakeData: Bool, backDays: Int) {
        self.backDays = backDays
        var moodEntries: [MoodEntry]?

        if fakeData {
            moodEntries = PersistenceController.shared.randomEntries(count: 10)
        } else {
            var daysAgo = Calendar.current.date(byAdding: .day, value: -backDays, to: Date())!
            daysAgo = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: daysAgo)!
            
            moodEntries = PersistenceController.shared.getData(startDate: daysAgo, endDate: Date(), includedDays: [1,2,3,4,5,6,7])
        }
        if let moodEntries = moodEntries {
            for (_, mood) in Mood.allValues.enumerated() {
                entries.append((mood, moodEntries.filter({
                    Int($0.moodValue) == mood.rawValue
                }).count))
            }
        }
        
        entries = entries.sorted(by: {
            $0.0.rawValue > $1.0.rawValue
        })
    }
    
    var body: some View {
        VStack {
            HStack {
                ForEach(entries, id: \.0) { (mood, value) in
                    Text(String(value))
                        .font(.title)
                        .fontWeight(.bold)
                        .foregroundColor(mood.color)
                        .frame(maxWidth: .infinity)
                }
            }
            
            Text(String(format: String(localized: "content_view_header_title"), self.backDays))
                .font(.body)
                .foregroundColor(Color(UIColor.systemGray))
                .frame(maxWidth: .infinity, alignment: .center)
                .padding(.top, 2)
        }
    }
}

struct SmallHeaderView_Previews: PreviewProvider {
    static var previews: some View {
        SmallRollUpHeaderView(fakeData: true, backDays: 30)
    }
}
