import Foundation
import SwiftDate
import DifferenceKit

protocol Dated {
    var added: Date { get }
    var updated: Date { get }
}

extension Vehicle: Dated {
    var updated: Date {
        Date(timeIntervalSince1970: self.updatedDate)
    }
    
    var added: Date {
        Date(timeIntervalSince1970: self.addedDate)
    }
}

extension AudioRecord: Dated {
    var updated: Date {
        Date(timeIntervalSince1970: self.getAddedDate())
    }
    
    var added: Date {
        Date(timeIntervalSince1970: self.getAddedDate())
    }
}

extension RandomAccessCollection where Element: Dated & Hashable & Differentiable {
    func groupedByDate(type: SortParameter = .updatedDate) -> [DateSection<Element>] {
        let now = Date()
        let monthStart = now.dateAtStartOf(.month)
        var sectionsIndices: [TimeInterval: Int] = [:]
        var sectionsArray: [DateSection<Element>] = []
        for vehicle in self {
            let date = self.date(of: type, for: vehicle)
            let dateInRegion = DateInRegion(date, region: Region.current)
            
            var key = dateInRegion.dateAtStartOf(.day).timeIntervalSince1970
            if date.isBeforeDate(monthStart, orEqual: false, granularity: .day) {
                key = dateInRegion.dateAtStartOf(.month).timeIntervalSince1970
            }
            
            if let index = sectionsIndices[key] {
                sectionsArray[index].append(vehicle)
            } else {
                sectionsArray.append(DateSection<Element>(timestamp: key, items: [vehicle]))
                sectionsIndices[key] = sectionsArray.count - 1
            }
        }
        
        return sectionsArray
    }
    
    func date(of type: SortParameter, for object: Dated) -> Date {
        switch type {
        case .addedDate: return object.added
        case .updatedDate: return object.updated
        }
    }
}
