//
//  FileManagerExtensions.swift
//  
//
//  Created by Thibaut Schmitt on 24/01/2022.
//

import Foundation

// swiftlint:disable force_unwrapping

extension FileManager {

    func getAllRegularFileIn(directory: String) -> [String] {
        var files = [String]()
        guard let enumerator = self.enumerator(at: URL(string: directory)!, includingPropertiesForKeys: [.isRegularFileKey], options: [.skipsHiddenFiles, .skipsPackageDescendants]) else {
            let error = ImagesError.unknown("Cannot enumerate file in \(directory)")
            print(error.description)
            Images.exit(withError: error)
        }

        for case let fileURL as URL in enumerator {
            do {
                let fileAttributes = try fileURL.resourceValues(forKeys: [.isRegularFileKey])
                if fileAttributes.isRegularFile! {
                    files.append(fileURL.relativePath)
                }
            } catch {
                let error = ImagesError.getFileAttributed(fileURL.relativePath, error.localizedDescription)
                print(error.description)
                Images.exit(withError: error)
            }
        }
        return files
    }

    func getAllImageSetFolderIn(directory: String) -> [String] {
        var files = [String]()
        guard let enumerator = self.enumerator(at: URL(string: directory)!, includingPropertiesForKeys: [.isDirectoryKey], options: [.skipsHiddenFiles, .skipsPackageDescendants]) else {
            let error = ImagesError.unknown("Cannot enumerate imageset directory in \(directory)")
            print(error.description)
            Images.exit(withError: error)
        }

        for case let fileURL as URL in enumerator {
            do {
                let fileAttributes = try fileURL.resourceValues(forKeys: [.isDirectoryKey])
                if fileAttributes.isDirectory! && fileURL.lastPathComponent.hasSuffix(".imageset") {
                    files.append(fileURL.lastPathComponent)
                }
            } catch {
                let error = ImagesError.getFileAttributed(fileURL.relativePath, error.localizedDescription)
                print(error.description)
                Images.exit(withError: error)
            }
        }
        return files
    }
}
