HistoryDBManager.swift 3.5 KB
//
//  HistoryDBManager.swift
//  browser
//
//  Created by Artem Talko on 17.10.2023.
//

import UIKit
import Realm
import RealmSwift

final class HistoryDBManager {
    static let shared = HistoryDBManager()
    private let realm: Realm
    
    private init() {
        do {
            self.realm = try Realm()
        } catch {
            fatalError("Error initializing Realm: \(error.localizedDescription)")
        }
    }
    
    //MARK: ADDING
    func saveToHistory(siteTitle: String, siteUrl: String, lastVisit: Date) {
        let historyCell = HistoryDataBase(siteTitle: siteTitle, siteUrl: siteUrl, lastVisit: lastVisit)
        do {
            try realm.write {
                realm.add(historyCell)
            }

        } catch {
            print("Error adding new tab: \(error.localizedDescription)")
        }
    }
    
    //MARK: GETTING
    func getHistory(sorted: Bool = false) -> [HistoryDataBase] {
        if sorted {
            let history = realm.objects(HistoryDataBase.self).sorted(byKeyPath: "lastVisit", ascending: false)
            return Array(history)
        } else {
            let history = realm.objects(HistoryDataBase.self)
            return Array(history)
        }
    }
    
    func getHistoryDataForTableView() -> ([HistoryElement]) {
        let stories = getHistory(sorted: true)
        return createHistoryData(elements: Array(stories))
    }

    func createHistoryData(elements: [HistoryDataBase]) -> ([HistoryElement]) {
        var groupedData: [String: [HistoryDataBase]] = [:]
        let dateFormatter = DateManager.shared.dateFormatter
        
        for data in elements {
            let formattedDate = dateFormatter.string(from: data.lastVisit)
            if groupedData[formattedDate] == nil {
                groupedData[formattedDate] = []
            }
            groupedData[formattedDate]?.append(data)
        }
        
        let result = groupedData.map({ HistoryElement( name: $0.key, stories: $0.value )})
        
        return result
    }
    
    func getFilteredHistory(filter: String) -> ([HistoryElement]) {
        let lowercasedFilter = filter.lowercased()
        let history = getHistory(sorted: true)
        let filteredHistory = history.filter({ $0.siteTitle.lowercased().contains(lowercasedFilter) || $0.siteUrl.lowercased().contains(lowercasedFilter)})
        return createHistoryData(elements: filteredHistory)
    }

    //MARK: DELETING
    func cleanHistory() {
        do {
            let history = realm.objects(HistoryDataBase.self)
            try realm.write {
                realm.delete(history)
            }
            
        } catch {
            print("Error cleaning history: \(error.localizedDescription)")
        }
    }
    
    func deleteHistoryInRange(startDate: Date) {
        do {
            let history = realm.objects(HistoryDataBase.self).filter("lastVisit >= %@", startDate)
            try realm.write {
                realm.delete(history)
            }

        } catch {
            print("Error deleting history within the specified time range: \(error.localizedDescription)")
        }
    }
    
    func deleteHistoryCell(tabId: String) {
        if let historyCellToDelete = realm.object(ofType: HistoryDataBase.self, forPrimaryKey: tabId) {
            do {
                try realm.write {
                    realm.delete(historyCellToDelete)
                }
                
            } catch {
                print("Error deleting history cell: \(error.localizedDescription)")
            }
        }
    }
    
  
}