import Foundation

class AnalyticsService: ObservableObject {
    enum Event: String {
        case bannerAdShown
        case bannerAdTapped
        case comment
        case search
    }
    
    enum Screen: String {
        case articleList
        case articleDetail
        case articleComments
        case authorDetail
        case eventDetail
        case eventTimes
    }
    
    private let repository: AnalyticsRepository
    
    init(repository: AnalyticsRepository) {
        self.repository = repository
    }
    
    func articleListWasViewed(listType: ContentService.BannerPosition) {
        switch listType {
            
        case .latest:
            repository.sendScreenView(Screen.articleList.rawValue, parameters: ["type":"latest"])
        case .trending:
            repository.sendScreenView(Screen.articleList.rawValue, parameters: ["type":"trending"])
        case .topic(topicId: let topicId):
            repository.sendScreenView(Screen.articleList.rawValue, parameters: ["type":"topic","topic_id":"\(topicId)"])
        default:
            return
        }
    }
    
    func articleWasViewed(postId: Int) {
        repository.sendScreenView(Screen.articleDetail.rawValue, parameters: ["post_id":"\(postId)"])
    }
    
    func articleCommentsWereViewed(postId: Int) {
        repository.sendScreenView(Screen.articleComments.rawValue, parameters: ["post_id":"\(postId)"])
    }
    
    func authorWasViewed(authorId: Int) {
        repository.sendScreenView(Screen.authorDetail.rawValue, parameters: ["author_id":"\(authorId)"])
    }
    
    func eventWasViewed(postId: Int) {
        repository.sendScreenView(Screen.eventDetail.rawValue, parameters: ["post_id":"\(postId)"])
    }
    
    func eventDetailsWereViewed(postId: Int) {
        repository.sendScreenView(Screen.eventTimes.rawValue, parameters: ["post_id":"\(postId)"])
    }
    
    func bannerAdWasShown(bannerId: String) {
        let parameters = ["banner_id":bannerId]
        repository.sendEvent(action: Event.bannerAdShown.rawValue, parameters: parameters)
    }
    
    func bannerAdWasTapped(bannerId: String) {
        let parameters = ["banner_id":bannerId]
        repository.sendEvent(action: Event.bannerAdTapped.rawValue, parameters: parameters)
    }
    
    func commentWasPosted(postId: Int, commentId: Int, inReplyTo: Int?) {
        var parameters = ["post_id":"\(postId)", "comment_id":"\(commentId)"]
        if let inReplyTo = inReplyTo {
            parameters["parent_comment_id"] = "\(inReplyTo)"
        }
        repository.sendEvent(action: Event.comment.rawValue, parameters: parameters)
    }
    
    func searchResultWasSelected(searchTerm: String) {
        let parameters = ["search_term":searchTerm]
        repository.sendEvent(action: Event.search.rawValue, parameters: parameters)
    }
}
