TabManager.swift 2.86 KB
//
//  DataBaseManager.swift
//  browser
//
//  Created by Artem Talko on 02.10.2023.
//

import Realm
import RealmSwift
import Alamofire
import UIKit

final class TabManager {
    static let shared = TabManager()
    private let realm: Realm
  
    
    private init() {
        do {
            self.realm = try Realm()
        } catch {
            fatalError("Error initializing Realm: \(error.localizedDescription)")
        }
    }

    
    func saveTabWithComplition(tabTitle: String, snapshotImage: UIImage?, tabUrl: String, completion: (Result<Void,Error>) -> Void) {
        let newTab = BrowserTabDataBase(tabTitle: tabTitle, snapshotImage: snapshotImage, tabUrl: tabUrl)
        
        do {
            try realm.write {
                realm.add(newTab)
                completion(.success(()))
            }
        } catch {
            print("Error adding new tab: \(error.localizedDescription)")
            completion(.failure(error))
        }
    }
    
    func saveTab(tabTitle: String, snapshotImage: UIImage?, tabUrl: String) {
        let newTab = BrowserTabDataBase(tabTitle: tabTitle, snapshotImage: snapshotImage, tabUrl: tabUrl)
        
        do {
            try realm.write {
                realm.add(newTab)
            }
        } catch {
            print("Error adding new tab: \(error.localizedDescription)")
        }
    }
    
    func updateTab(tabId: String, newTabTitle: String, newSnapshotImage: UIImage?, newTabUrl: String, completion: (Result<Void, Error>) -> Void) {
           if let tabToUpdate = realm.object(ofType: BrowserTabDataBase.self, forPrimaryKey: tabId) {
               do {
                   try realm.write {
                       tabToUpdate.tabTitle = newTabTitle
                       tabToUpdate.TabUrl = newTabUrl
                       if let image = newSnapshotImage {
                           tabToUpdate.snapshotImageData = image.pngData()
                       }
                       completion(.success(()))
                   }
               } catch {
                   print("Error updating tab: \(error.localizedDescription)")
                   completion(.failure(error))
               }
           } else {
               let error = NSError(domain: "Error", code: 404, userInfo: [NSLocalizedDescriptionKey: "Tab not found"])
               completion(.failure(error))
           }
       }
    
    func getAllTabs() -> [BrowserTabDataBase] {
        let savedTabs = realm.objects(BrowserTabDataBase.self)
        return Array(savedTabs)
    }
    
    func deleteTab(tabId: String) {
        if let tabToDelete = realm.object(ofType: BrowserTabDataBase.self, forPrimaryKey: tabId) {
            do {
                try realm.write {
                    realm.delete(tabToDelete)
                }
            } catch {
                print("Error deleting tab: \(error.localizedDescription)")
            }
        }
    }
}