//
//  Random.swift
//  Feels
//
//  Created by Trey Tartt on 1/9/22.
//

import Foundation
import SwiftUI

struct Constants {
    static let groupShareId = "group.com.88oak.ifeel"
}

struct GroupUserDefaults {
    static var groupDefaults: UserDefaults {
        return UserDefaults(suiteName: Constants.groupShareId)!
    }
}

typealias MoodGroupingMetrics = (mood: Mood, total: Int, percent: Float)

class Random {
    static var tomorrowMidnightThirty: Date {
        let components = DateComponents(hour: 0, minute: 30, second: 0)
        var updateTime = Date()
        if let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: Date()),
           let tomorrowMorning = Calendar.current.date(byAdding: components, to: tomorrow) {
            updateTime = tomorrowMorning
        }
        return updateTime
    }
    
    static func weekdayName(fromDate date: Date) -> String {
        let weekday = Calendar.current.component(.weekday, from: date)
        let calendar = Calendar.current
        let dayIndex = ((weekday - 1) + (calendar.firstWeekday - 1)) % 7
        return calendar.weekdaySymbols[dayIndex]
    }
    
    static func monthName(fromMonthInt: Int) -> String {
        let monthName = DateFormatter().monthSymbols[fromMonthInt-1]
        return monthName
    }
    
    static func dayFormat(fromDate date: Date) -> String {
        let components = Calendar.current.dateComponents([.day], from: date)
        let day = components.day!
        
        let formatter = NumberFormatter()
        formatter.numberStyle = .ordinal
        return formatter.string(from: NSNumber(integerLiteral: day)) ?? ""
    }
    
    static func createTotalPerc(fromEntries entries: [MoodEntry]) -> [MoodGroupingMetrics] {
        var returnData = [MoodGroupingMetrics]()
        
        for (_, mood) in Mood.allValues.enumerated() {
            let moodEntries = entries.filter({
                Int($0.moodValue) == mood.rawValue
            })
            let total = moodEntries.count
            let perc = (Float(total) / Float(entries.count)) * 100
            returnData.append((mood, total, perc))
        }
        
        returnData = returnData.sorted(by: {
            $0.0.rawValue > $1.0.rawValue
        })
        
        return returnData
    }
}

extension Date: RawRepresentable {
    public var rawValue: String {
        self.timeIntervalSinceReferenceDate.description
    }
    
    public init?(rawValue: String) {
        self = Date(timeIntervalSinceReferenceDate: Double(rawValue) ?? 0.0)
    }
    
    func startOfMonth() -> Date {
        let interval = Calendar.current.dateInterval(of: .month, for: self)
        return (interval?.start.toLocalTime())! // Without toLocalTime it give last months last date
    }

    func endOfMonth() -> Date {
        let interval = Calendar.current.dateInterval(of: .month, for: self)
        return interval!.end
    }
    
    func toLocalTime() -> Date {
        let timezone    = TimeZone.current
        let seconds     = TimeInterval(timezone.secondsFromGMT(for: self))
        return Date(timeInterval: seconds, since: self)
    }
    
    var weekday: Int {
        Calendar.current.component(.weekday, from: self)
    }
    
    var firstDayOfTheMonth: Date {
        Calendar.current.dateComponents([.calendar, .year,.month], from: self).date!
    }
}


struct RoundedCorner: Shape {
    
    var radius: CGFloat = .infinity
    var corners: UIRectCorner = .allCorners
    
    func path(in rect: CGRect) -> Path {
        let path = UIBezierPath(roundedRect: rect, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        return Path(path.cgPath)
    }
}

extension View {
    func cornerRadius(_ radius: CGFloat, corners: UIRectCorner) -> some View {
        clipShape( RoundedCorner(radius: radius, corners: corners) )
    }
    
    func snapshot() -> UIImage {
        let controller = UIHostingController(rootView: self)
        let view = controller.view
        let targetSize = controller.view.intrinsicContentSize
        view?.bounds = CGRect(origin: .zero, size: targetSize)
        view?.backgroundColor = .clear
        let renderer = UIGraphicsImageRenderer(size: targetSize)
        return renderer.image { _ in
            view?.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
        }
    }
    
    func asImage(size: CGSize) -> UIImage {
        let controller = UIHostingController(rootView: self)
        controller.view.bounds = CGRect(origin: .zero, size: size)
        let image = controller.view.asImage()
        return image
    }
}

extension UIView {
    func asImage() -> UIImage {
        let format = UIGraphicsImageRendererFormat()
        format.scale = 1
        return UIGraphicsImageRenderer(size: self.layer.frame.size, format: format).image { context in
            self.drawHierarchy(in: self.layer.bounds, afterScreenUpdates: true)
        }
    }
}

extension Date {
    static func dates(from fromDate: Date, to toDate: Date) -> [Date] {
        var dates: [Date] = []
        var date = fromDate
        
        while date <= toDate {
            dates.append(date)
            guard let newDate = Calendar.current.date(byAdding: .day, value: 1, to: date) else { break }
            date = newDate
        }
        return dates
    }
}

extension Color {
    static func random() -> Self {
        Self(
            red: .random(in: 0...1),
            green: .random(in: 0...1),
            blue: .random(in: 0...1)
        )
    }
}
