//  Copyright © 2019 650 Industries. All rights reserved.

import Foundation

/**
 * Data class that represents an individual asset. The filename is autogenerated if not explicitly
 * set (it should be explicitly set when originating from a database query).
 */
@objc(EXUpdatesAsset)
@objcMembers
public final class UpdateAsset: NSObject {
  /**
   * properties determined by asset source
   */

  public var key: String?
  public let type: String?
  public var url: URL?
  public var metadata: [String: Any]?
  public var mainBundleDir: String? // used for embedded assets
  public var mainBundleFilename: String? // used for embedded assets
  public var isLaunchAsset = false
  public var extraRequestHeaders: [String: Any]?
  public var expectedHash: String? // base64url-encoded sha-256

  /**
   * properties determined at runtime by updates implementation
   */

  public var downloadTime: Date?
  public var contentHash: String? // base64url-encoded sha-256
  public var headers: [String: Any]?

  /**
   * properties determined by updates database
   */

  public var assetId = 0

  public required init(key: String?, type: String?) {
    self.key = key
    self.type = type
  }

  public lazy var filename: String = {
    var fileExtension = ""
    if let type = type {
      if type.hasPrefix(".") {
        fileExtension = type
      } else {
        fileExtension = "." + type
      }
    }

    guard let key = key else {
      // create a filename that's unlikely to collide with any other asset
      // swiftlint:disable:next legacy_random
      return String(format: "asset-%d-%u%@", arguments: [Int(Date().timeIntervalSince1970), arc4random(), fileExtension])
    }

    return key + fileExtension
  }()
}
