//
//  ICloudDriveManager.swift
//  Zockerhoehle
//
//  Created by Julian-Steffen Müller on 18.05.21.
//  Copyright © 2021 Julian-Steffen Müller. All rights reserved.
//

import Foundation
import UIKit

class ICloudManager {
    static let shared : ICloudManager = ICloudManager();
    
    static let relative_seperator : [String] = ["iCloud~Zockerhoehle", "Documents"]
    
    static var backup_folder : URL? {
        get {
            return documents_folder?.appendingPathComponent("backup")
        }
    }
    
    static var documents_folder : URL? {
        get {
            return FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Documents")
        }
    }
    
    static public func relativePathFrom(url : URL) -> String? {
        return url.relative_path_after(pathComponent: relative_seperator) ?? .none
    }
    
    static public func fileExists(at path : String?) -> Bool {
        guard let path = path else { return false }
        if path == "" { return false }
        
        if let url = documents_folder?.appendingPathComponent(path) {
            return FileManager.default.fileExists(atPath: url.path)
        }
        
        return false;
    }
    
    static public func imageFrom(path : String?) -> UIImage? {
        guard let path = path else { return .none }
        
        do {
            let url = documents_folder?.appendingPathComponent(path)
            let imageData = try Data(contentsOf: url!)
            
            return UIImage(data: imageData)!
        }catch {
            return .none
        }
    }
    
    static public func inICloudContainer(url : URL?) -> Bool {
        guard let url = url else { return false }
        
        for component in url.pathComponents {
            if relative_seperator.count > 0 &&  component == relative_seperator[0] {
                return true
            }
        }
        
        return false
    }
    
    public func preload_all_data() -> Bool {
        guard let docs_url = ICloudManager.documents_folder else { return false }
        
        do {
            try FileManager.default.startDownloadingUbiquitousItem(at: docs_url)
            
            return true
        }catch{
            return false
        }
        
    }
    
    private init() {
        
    }
}
