//
//  DescriptiveError.swift
//  TagTunes
//
//  Created by Kim Wittenburg on 06.09.15.
//  Copyright © 2015 Kim Wittenburg. All rights reserved.
//

import Foundation

/// A custom error class that wraps another error to display a more descriptive
/// error description than for example "The operation couldn't be completed."
public class DescriptiveError: NSError {
    
    /// Initializes the receiver with the specified `underlyingError`.
    /// The underlying error is added to the receiver's `userInfo` dictionary as
    /// is the specified dictionary.
    public init(underlyingError: NSError, userInfo: [NSString: AnyObject]?) {
        var actualUserInfo = userInfo ?? [NSString: AnyObject]()
        actualUserInfo[NSUnderlyingErrorKey] = underlyingError
        super.init(domain: underlyingError.domain, code: underlyingError.code, userInfo: actualUserInfo)
    }

    public required init?(coder aDecoder: NSCoder) {
        fatalError("DescriptiveError instances should not be encoded.")
    }
    
    /// Returns the value for the NSUnderlyingErrorKey in the error's `userInfo`
    /// dictionary as an `NSError` instance.
    public var underlyingError: NSError {
        return userInfo[NSUnderlyingErrorKey] as! NSError
    }
    
    override public var localizedDescription: String {
        if domain == NSURLErrorDomain {
            switch code {
            case NSURLErrorNotConnectedToInternet:
                return NSLocalizedString("You are not connected to the internet.", comment: "Error message informing the user that he is not connected to the internet.")
            case NSURLErrorTimedOut:
                return NSLocalizedString("The network request timed out.", comment: "Error message informing the user that the network request timed out.")
            default: break
            }
        }
        return super.localizedDescription
    }
    
    override public var localizedRecoverySuggestion: String? {
        if domain == NSURLErrorDomain {
            switch code {
            case NSURLErrorNotConnectedToInternet:
                return NSLocalizedString("Please check your network connection and try again.", comment: "Error recovery suggestion for 'not connected to the internet' error.")
            case NSURLErrorTimedOut:
                return NSLocalizedString("Please check your network connection and try again. If that does not help it may be possible that Apple's Search API service is currently offline. Please try again later.", comment: "Error recovery suggestion for 'time out' error.")
            default: break
            }
        }
        return super.localizedRecoverySuggestion
    }
    
}