//
// Created by Alexander Zalutskiy on 15.05.15.
// Copyright (c) 2015 Alexander Zalutskiy. All rights reserved.
//

import Foundation
import UIKit

enum Language : String {
	case Russian = "ru"
	case English = "en"
	case Kazakh = "kk"
	
	var locale: NSLocale {
		switch self {
		case .Russian:
			return NSLocale(localeIdentifier: "ru")
		case .English:
			return NSLocale(localeIdentifier: "en")
		case .Kazakh:
			return NSLocale(localeIdentifier: "kk")
		}
	}
  
  var forTelecom: String {
    switch self {
    case .Russian:
      return "rus"
    case .English:
      return "eng"
    case .Kazakh:
      return "kaz"
    }
  }
	
	var apiPart: String {
		if self != .Kazakh {
			return self.rawValue
		} else {
			return "kz"
		}
	}
}

private var appLanguageBundle: NSBundle!
private var appLanguageCode: Language!
private let appLanguageKey = "appLanguage"
private let stringNotFoundValue = "???"
private let langFileExtension = "lproj"
private let localizationTableName = "Localization"

private let lockQueue = dispatch_queue_create("com.simplecode.LanguageQueue", nil)

class AppLocalization {
	
	static func initialize() {
		let defaultLanguage: Language!
		if let key = NSUserDefaults.standardUserDefaults().objectForKey(appLanguageKey) as? String {
			defaultLanguage = Language(rawValue: key)
		} else {
			defaultLanguage = .Russian
		}
		AppLocalization.setLanguage(defaultLanguage)
	}
	
	class func setLanguage(language: Language) {
		dispatch_sync(lockQueue) {
			appLanguageCode = language
			let langPath = NSBundle.mainBundle().pathForResource(appLanguageCode.rawValue, ofType: langFileExtension)
			appLanguageBundle = NSBundle(path: langPath!)
			NSUserDefaults.standardUserDefaults().setValue(appLanguageCode.rawValue, forKey: appLanguageKey)
			
			NSNotificationCenter.defaultCenter().postNotificationName("AppLocalizationLanguageChange", object: nil)
		}
	}
	
	class func language() -> Language {
		return appLanguageCode
	}
	
	class func stringWithKey(key: String) -> String {
		return appLanguageBundle.localizedStringForKey(key, value: stringNotFoundValue, table: localizationTableName)
	}
	
	class func pathForResource(name: String?, ofType type: String?) -> String? {
		return appLanguageBundle.pathForResource(name, ofType: type)
	}
}

public func LocalizedString(key: String, description: String? = nil) -> String {
	return AppLocalization.stringWithKey(key)
}

public func LS(key: String, description: String? = nil) -> String {
  return LocalizedString(key)
}

//public func LS(key: String) -> String {
//	return LocalizedString(key)
//}

prefix operator § { }

prefix func § (key: String) -> String {
	return LS(key)
}

public func LocalizedPathForResource(key: String?, ofType type: String?) -> String? {
	return AppLocalization.pathForResource(key, ofType: type)
}

protocol LocalizedParent {
  var localizedId: String { get }
}

protocol Localized: LocalizedParent {
  func localize()
}

protocol LocalizedChild {
  //	func localizeWithParent(parent: LocalizedParent, localizedId: String)
  func localizeWithParent(parent: LocalizedParent, localizedId: String, args: CVarArgType...)
}

//extension UIButton: LocalizedChild {
//  
//  func localizeWithParent(parent: LocalizedParent, localizedId: String, args: CVarArgType...) {
//    
//    let textNormal = LocalizedString("\(parent.localizedId).button.\(localizedId)")
//    if textNormal != stringNotFoundValue {
//      setTitle(String(format: textNormal, locale: appLanguageCode.locale,
//        arguments: args), forState: .Normal)
//    }
//  }
//}

extension UILabel: LocalizedChild {
  
  func localizeWithParent(parent: LocalizedParent, localizedId: String, args: CVarArgType...) {
    
    let key = "\(parent.localizedId).label.\(localizedId)"
    let title = LocalizedString(key)
    if title != stringNotFoundValue {
      text = String(format: title, locale: appLanguageCode.locale,
        arguments: args)
      sizeToFit()
    }
  }
}

extension UITextField: LocalizedChild {
  
  func localizeWithParent(parent: LocalizedParent, localizedId: String, args: CVarArgType...) {
    
    let placeholderText = LocalizedString("\(parent.localizedId).text_field.\(localizedId).placeholder")
    if placeholderText != stringNotFoundValue {
      placeholder = String(format: placeholderText,
        locale: appLanguageCode.locale, arguments: args)
    }
  }
}

extension UIViewController: Localized {
  var localizedId: String {
    fatalError("Required override var")
  }
  
  func localize() {
    let text = LS("\(self.localizedId).title")
    title = text
  }
}

