// // SmallHeaderView.swift // Feels (iOS) // // Created by Trey Tartt on 1/28/22. // import SwiftUI struct SmallRollUpHeaderView: View { @Binding var viewType: MainSwitchableViewType @Binding var backDays: Int typealias Model = (mood: Mood, total: Int, percent: Float) private var entries = [Model]() init(fakeData: Bool, backDays: Binding, viewType: Binding) { self._viewType = viewType self._backDays = backDays var moodEntries: [MoodEntry]? if fakeData { moodEntries = PersistenceController.shared.randomEntries(count: 10) } else { var daysAgo = Calendar.current.date(byAdding: .day, value: -self.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]) } let totalEntryCount = moodEntries?.count ?? 0 if let moodEntries = moodEntries { for (_, mood) in Mood.allValues.enumerated() { let moodEntries = moodEntries.filter({ Int($0.moodValue) == mood.rawValue }) let total = moodEntries.count let perc = (Float(total) / Float(totalEntryCount)) * 100 entries.append((mood, total, perc)) } } entries = entries.sorted(by: { $0.0.rawValue > $1.0.rawValue }) } private func textView(forModel model: Model) -> Text { switch viewType { case .total: return Text(String(model.total)) case .percentageCircle: return Text("\(model.percent, specifier: "%.0f")%") case .percentage: return Text("\(model.percent, specifier: "%.0f")%") } } private var modelTextViews: some View { HStack { ForEach(entries, id: \.0) { model in textView(forModel: model) } } } private var viewOnViewtype : some View { HStack { switch viewType { case .total, .percentageCircle: circularViews case .percentage: textViews } } } private var textViews: some View { HStack { ForEach(entries, id: \.0) { model in textView(forModel: model) .font(.title2) .fontWeight(.bold) .lineLimit(1) .foregroundColor(model.mood.color) .frame(width: 50, height: 50) } } .padding([.top, .bottom]) } private var circularViews: some View { HStack { ForEach(entries, id: \.0) { model in ZStack { Circle().fill(model.mood.color) .frame(width: 50, height: 50) textView(forModel: model) .font(.title3) .fontWeight(.bold) .frame(width: 40, height: 40) .scaledToFill() .minimumScaleFactor(0.5) .lineLimit(1) .foregroundColor(Color(UIColor.white)) } } } .padding([.top, .bottom]) } var body: some View { viewOnViewtype .frame(minWidth: 0, maxWidth: .infinity) } } struct SmallHeaderView_Previews: PreviewProvider { static var previews: some View { SmallRollUpHeaderView(fakeData: true, backDays: .constant(30), viewType: .constant(.total)) SmallRollUpHeaderView(fakeData: true, backDays: .constant(7), viewType: .constant(.total)) } }