/*
 *  Copyright © 2016, 2017, Oracle and/or its affiliates. All rights reserved.
 *  This software is dual-licensed to you under the MIT License (MIT) and
 *  the Universal Permissive License (UPL). See the LICENSE file in the root
 *  directory for license terms. You may choose either license, or both.
 */

import Foundation

/**
 * Construct collecting information about available files
 */
class FileParser {
    
    static let sharedInstance = FileParser()
    
    var _excludesFileExtensions = [String]()
    
    var excludesFileExtensions: [String]? {
        get {
            return _excludesFileExtensions.map({$0.lowercased()})
        }
        set {
            if let newValue = newValue {
                _excludesFileExtensions = newValue
            }
        }
    }
    
    var excludesFilepaths: [URL]?
    
    let filemgr = FileManager.default
    
    func documentsURL() -> URL {
        return filemgr.urls(for: .documentDirectory,
                            in: .userDomainMask)[0] as URL
    }
    
    func tempURL() -> URL {
        let tmpDir = filemgr.temporaryDirectory
        return URL(fileURLWithPath: tmpDir.path, isDirectory: true)
    }
    
    func resourceURL() -> URL {
        let docsPath = Bundle.main.resourcePath!
        return URL(fileURLWithPath: docsPath, isDirectory: true)
    }
    
    func filesForDirectory(directoryURL: URL) -> [FileRep]  {
        var files = [FileRep]()
        var filePaths = [URL]()
        // Get directory content.
        do  {
            filePaths = try self.filemgr.contentsOfDirectory(at: directoryURL,
                                includingPropertiesForKeys: nil, options: [])
        } catch {
            return files
        }
        // Parse the file paths.
        for filePath in filePaths {
            let file = FileRep(filePath: filePath)
            if let excludesFileExtensions = excludesFileExtensions,
                    let fileExtensions = file.fileExtension,
                    excludesFileExtensions.contains(fileExtensions) {
                continue
            }
            if let excludesFilepaths = excludesFilepaths,
                    excludesFilepaths.contains(file.filePath) {
                continue
            }
            if file.displayName.isEmpty == false {
                files.append(file)
            }
        }
        // Sort the file list.
        files = files.sorted(){$0.displayName < $1.displayName}
        return files
    }
}
