//
//  CustomDateTransform.swift
//  iPOS
//
//  Created by BBC on 20/10/16.
//  Copyright © 2016 BBC. All rights reserved.
//

import Foundation
import ObjectMapper
import UIKit
import AVFoundation
import Firebase
import Fabric
import Crashlytics

class Util {

    static var splashScreen: UIActivityIndicatorView = UIActivityIndicatorView()
    
    static func CustomDateTransform() -> TransformOf<Date, String> {
        let df = DateFormatter()
        df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
        
        let transform = TransformOf<Date, String>(fromJSON: { (value: String?) -> Date? in
            guard let valueString = value else { return nil}
            let index = valueString.index(valueString.startIndex, offsetBy: 19)
            let value = String(valueString[..<index])
            return df.date(from: value)
        }, toJSON: { (value: Date?) -> String? in
            if let value = value {
                return df.string(from: value)
            }
            return nil
        })
        return transform
    }
    
    static func CustomDoubleTransform() -> TransformOf<Double, String> {
        let transform = TransformOf<Double, String>(fromJSON: { (value: String?) -> Double? in
            guard let value = value else { return nil}
            return Double.init(value)?.rounded(toPlaces: 2)
        }, toJSON: { (value: Double?) -> String? in
            if let value = value {
                return value.description
            }
            return nil
        })
        return transform
    }
    
    static func CustomDoubleTransformQuantities() -> TransformOf<Double, String> {
        let transform = TransformOf<Double, String>(fromJSON: { (value: String?) -> Double? in
            guard let value = value else { return nil}
            return Double.init(value)
        }, toJSON: { (value: Double?) -> String? in
            if let value = value {
                return value.description
            }
            return nil
        })
        return transform
    }
    
    static func CustomDecimalTransform() -> TransformOf<Decimal, String> {
        let transform = TransformOf<Decimal, String>(fromJSON: { (value: String?) -> Decimal? in
            guard let value = value else { return nil}
            return Decimal.init(string: value)
        }, toJSON: { (value: Decimal?) -> String? in
            if let value = value {
                return value.description
            }
            return nil
        })
        return transform
    }
    
    static func CustomImageTransform() -> TransformOf< UIImage, String> {
        let transform = TransformOf<UIImage, String>(fromJSON: { (value: String?) -> UIImage? in
            guard let value = value else { return nil}
            let dataDecoded:NSData = NSData(base64Encoded: value, options: NSData.Base64DecodingOptions(rawValue: 0))!
            let decodedimage:UIImage = UIImage(data: dataDecoded as Data)!
            return decodedimage
        }, toJSON: {(value: UIImage?)-> String? in
            guard let value = value else { return nil }
            let imageData: NSData = value.pngData()! as NSData
            let base64Data = imageData.base64EncodedData(options: NSData.Base64EncodingOptions.lineLength64Characters)
            let binaryData = NSString(data: base64Data, encoding: String.Encoding.utf8.rawValue) as String?
            return binaryData
        })
        return transform
    }
    
    static func CustomUuidTransform() -> TransformOf<UUID, String> {
        
        let transform = TransformOf<UUID, String>(fromJSON: { (value: String?) -> UUID? in
            guard let value = value else { return nil}
            return UUID.init(uuidString: value)
        }, toJSON: { (value: UUID?) -> String? in
            if let value = value {
                return value.description
            }
            return nil
        })
        return transform
    }

    static func DoubleToString(_ double:  Double) -> String{
        let fmt = NumberFormatter()
        fmt.usesGroupingSeparator = true
        fmt.maximumFractionDigits = 2
        fmt.minimumFractionDigits = 2
        
        fmt.locale = Locale.current
        if settings.userSettings.twoLettersISOCultureCode.isEmpty == false{
            fmt.locale = Locale.init(identifier: settings.userSettings.twoLettersISOCultureCode)
        }
        
        fmt.numberStyle = .decimal
        
        return fmt.string(from: NSNumber(value: double))!
    }
    
    static func DoubleToString(_ double:  Double, decimalPlaces: Int) -> String{
        let fmt = NumberFormatter()
        fmt.usesGroupingSeparator = true
        fmt.maximumFractionDigits = decimalPlaces
        fmt.minimumFractionDigits = decimalPlaces
        
        fmt.locale = Locale.current
        if settings.userSettings.twoLettersISOCultureCode.isEmpty == false{
            fmt.locale = Locale.init(identifier: settings.userSettings.twoLettersISOCultureCode)
        }
        
        fmt.numberStyle = .decimal
        
        return fmt.string(from: NSNumber(value: double))!
    }
    
    static func DoubleToStringQuantity(_ double:  Double, decimalPlaces: Int) -> String{
        let fmt = NumberFormatter()
        fmt.usesGroupingSeparator = true
        fmt.maximumFractionDigits = decimalPlaces
        fmt.minimumFractionDigits = decimalPlaces
        fmt.decimalSeparator = "."
        fmt.numberStyle = .decimal
        
        return fmt.string(from: NSNumber(value: double))!
    }
    
    static func DoubleToStringWithPointSeparator(_ double:  Double) -> String{
        let fmt = NumberFormatter()
        fmt.usesGroupingSeparator = false
        fmt.maximumFractionDigits = 2
        fmt.minimumFractionDigits = 2
        fmt.decimalSeparator = "."
        fmt.numberStyle = .decimal
        
        return fmt.string(from: NSNumber(value: double))!
    }
    
    static func DoubleToStringNoDecimals(_ double:  Double) -> String{
        let fmt = NumberFormatter()
        fmt.usesGroupingSeparator = false
        fmt.maximumFractionDigits = 0
        fmt.minimumFractionDigits = 0
        fmt.decimalSeparator = ""
        fmt.numberStyle = .none
        
        return fmt.string(from: NSNumber(value: double))!
    }
    
    static func DoubleToDoubleRoundedWithTwoDecimalPlaces(_ double: Double) -> Double{
        return Double(round(double * 100) / 100)
    }
    
    static func DoubleToStringWithTwoDecimals(_ double: Double) -> String{
        return String(format: "%.2f", double)
    }
    
    static func DoubleToStringWithOneDecimal(_ double: Double) -> String{
        return String(format: "%.1f", double)
    }
    
    static func DateToShortDateString(day: Int, month: Int, year: Int) -> String {
        var dateString = ""
        if day < 10 {
            dateString.append("0\(day)/")
        }
        else{
            dateString.append("\(day)/")
        }
        if month < 10 {
            dateString.append("0\(month)/")
        }
        else{
            dateString.append("\(month)/")
        }
        
        dateString.append("\(year)")
        
        return dateString
    }

    static func DateToShortDateString(date: Date) -> String {
        let df = DateFormatter()
        df.dateFormat = "dd/MM/yyyy"
        return df.string(from: date)
    }
    
    static func DateToYYYYMMDDMinusSeparator(date: Date) -> String {
        let df = DateFormatter()
        df.dateFormat = "yyyy-MM-dd"
        return df.string(from: date)
    }
    
    static func DateToYYMMDD(date: Date) -> String {
        let df = DateFormatter()
        df.dateFormat = "yyMMdd"
        return df.string(from: date)
    }
    
    static func DateToLongDateString(date: Date) -> String {
        let df = DateFormatter()
        df.dateFormat = "yyyy-MM-dd'T'HH:mm:00"
        return df.string(from: date)
    }
    
    static func DateToFullDateString(date: Date) -> String {
        let df = DateFormatter()
        df.dateFormat = "yyyy-MM-dd HH:mm"
        return df.string(from: date)
    }
    
    static func DateToDayWithoutYearString(date: Date) -> String {
        let df = DateFormatter()
        df.dateFormat = "dd-MM"
        return df.string(from: date)
    }
    
    static func DateToTimeString(date: Date) -> String {
        let df = DateFormatter()
        df.dateFormat = "HH:mm"
        return df.string(from: date)
    }
    
    static func DateToCompleteDateString(date: Date) -> String {
        let df = DateFormatter()
        df.dateFormat = "EEE dd MMM yyyy HH:mm"
        return df.string(from: date)
    }
    
    static func DateToShortDateStringNonFiscalPrinter(date: Date) -> String {
        let df = DateFormatter()
        df.dateFormat = "dd-MM-yyyy"
        return df.string(from: date)
    }
    
    static func DateToMaterialDesignString(date: Date) -> String {
        let df = DateFormatter()
        let diff: Int = -Int(date.timeIntervalSinceNow)
        
        if (diff < 60){
            return Util.getString("Just Now")
        }
        else if (diff > 60 && diff < 3600) {
            return (diff/60).description + " " + Util.getString("mins ago")
        }
        else if (diff > 3600 && diff < 2*3600) {
            return (diff/3600).description + " " + Util.getString("hour ago")
        }
        else if (diff > 2*3600 && diff < 86400) {
            return (diff/3600).description + " " + Util.getString("hours ago")
        }
        else if (diff > 86400 && diff < 7*86400) {
            df.dateFormat = "EEEE HH:mm"
           return  df.string(from: date)
        }
        else if (diff > 7*86400 && diff < 6*4*7*86400) {
            df.dateFormat = "dd MMM"
            return  df.string(from: date)
        }
        else {
            df.dateFormat = "dd-MMM-yyyy"
            return df.string(from: date)
        }
    }
    
    static func DateToLongDateISO(date: Date) -> String {
        let df = DateFormatter()
        df.dateFormat = "yyyyMMddHHmmss"
        return df.string(from: date)
    }
    
    static func StringDateToYYYYMMDDMinusSeparator(stringDate: String) -> Date {
        let df = DateFormatter()
        df.dateFormat = "dd/MM/yyyy"
        if let date = df.date(from: stringDate) {
            return date
        }
        return Date()
    }
    
    static public func CreateSplashScreen(view: UIView){
        self.splashScreen = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.gray)
        self.splashScreen.color = UIColor.red
        self.splashScreen.center = view.center
        view.addSubview(self.splashScreen)
    }
    
    static public func SetNetworkActivityIndicatorVisibilty(text: String?, visible: Bool){
        UIApplication.shared.isNetworkActivityIndicatorVisible = visible
        if visible{
            ActivityView.showActivityView(text!, disableUI: true)
        }
        else{
            ActivityView.hide(false, animated: true)
        }
    }
    
    static func showMultipleAlert(viewController: UIViewController, title: String, msgs: [String]){
        var messages = msgs
        guard messages.count > 0 else { return }
        
        let message = messages.first
        
        func removeAndShowNextMessage() {
            messages.removeFirst()
            self.showMultipleAlert(viewController: viewController, title: title, msgs: messages)
        }
        
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alertController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
        alertController.addAction(UIAlertAction(title: "OK", style: .default){ (action) in
            removeAndShowNextMessage()
        })
        
        viewController.present(alertController, animated: true, completion: nil)
    }
    
    static func AlertRequiredField(field: UITextField, fieldName: String, viewController: UIViewController){
        let title: String = Util.getString("Warning")
        let message: String = fieldName + " " + Util.getString("is required!")
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        let OKAction = UIAlertAction(title: "OK", style: .default, handler : { (action) -> Void in
            field.becomeFirstResponder()
            return
        })
        alertController.addAction(OKAction)
        
        viewController.present(alertController, animated: true, completion: nil)
    }
    
    static func AlertRequiredField(fieldName: String, viewController: UIViewController){
        let title: String = Util.getString("Warning")
        let message: String = fieldName + " " + Util.getString("is required!")
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        let OKAction = UIAlertAction(title: "OK", style: .default, handler : { (action) -> Void in
            return
        })
        alertController.addAction(OKAction)
        
        viewController.present(alertController, animated: true, completion: nil)
    }
    
    static func GeneralAlert(viewController: UIViewController, message: String){
        let title: String = "iPOS"

        self.GeneralAlert(viewController: viewController, message: message, title: title)
    }
    
    static func GeneralAlert(viewController: UIViewController, message: String, title: String){
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        let OKAction = UIAlertAction(title: "OK", style: .default, handler : { (action) -> Void in
            return
        })
        alertController.addAction(OKAction)
        
        viewController.present(alertController, animated: true, completion: nil)
    }
    
    static func GeneralAlertAutoDismiss(viewController: UIViewController, message: String,time: Double){
        let title: String = "iPOS"
        
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
      
        viewController.present(alertController, animated: true, completion: nil)
        
        let when = DispatchTime.now() + time
        DispatchQueue.main.asyncAfter(deadline: when){
            alertController.dismiss(animated: true, completion: nil)
        }
    }
    
    static func GeneralAlertWithAction(viewController: UIViewController, message: String, generalAction:@escaping (() -> ())){
        GeneralAlertWithAction(viewController: viewController, title: Util.getString("Warning"), message: message, generalAction: generalAction)
    }
    
    static func GeneralAlertWithAction(viewController: UIViewController, title: String, message: String, generalAction:@escaping (() -> ())){
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        let OkAction = UIAlertAction(title: "OK", style: .default, handler : { (action) -> Void in
            generalAction()
        })
        
        alertController.addAction(OkAction)
        
        viewController.present(alertController, animated: true, completion: nil)
    }
    
    static func GeneralAlertAutoDismissWithAction(viewController: UIViewController, message: String,time: Double, action:@escaping (() -> ())){
        let title: String = "iPOS"
        
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        viewController.present(alertController, animated: true, completion: nil)
        
        let when = DispatchTime.now() + time
        DispatchQueue.main.asyncAfter(deadline: when){
            alertController.dismiss(animated: true, completion: {
                action()
            })
        }
    }
    
    static func AlertOperationNotAllowed(viewController: UIViewController,message: String){
        let title: String = Util.getString("Not allowed")
        
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        let OKAction = UIAlertAction(title: "OK", style: .default, handler : { (action) -> Void in
            return
        })
        alertController.addAction(OKAction)
        
        viewController.present(alertController, animated: true, completion: nil)
    }
    
    static func AlertSystemError(viewController: UIViewController, message: String){
        let title: String = Util.getString("Oops, something went wrong")
        
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        let OKAction = UIAlertAction(title: "OK", style: .default, handler : { (action) -> Void in
            return
        })
        alertController.addAction(OKAction)
        
        viewController.present(alertController, animated: true, completion: nil)
    }
    
    static func AlertSystemError(viewController: UIViewController){
        AlertSystemError(viewController: viewController, message: Util.getString("The operation cannot be completed for the moment. Please try again later."))
    }
    
    static func scannedBarcodeNotFoundAlert(code: String,message: String, viewController: UIViewController, captureSession: AVCaptureSession ){
        let title: String = code
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        let OKAction = UIAlertAction(title: "OK", style: .default, handler : { (action) -> Void in
            
            viewController.dismiss(animated: true)
            captureSession.startRunning()
        })
        alertController.addAction(OKAction)
        viewController.present(alertController, animated: true, completion: nil)
    }
    
    static func searchedBarcodeNotFoundAlert(code: String,message: String, viewController: UIViewController){
        let title: String = code
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        let OKAction = UIAlertAction(title: "OK", style: .default, handler : { (action) -> Void in
            return
        })
        alertController.addAction(OKAction)
        viewController.present(alertController, animated: true, completion: nil)
    }
    
    static func AlertRetryAction(viewController: UIViewController, title: String, message: String, actionOnRetry:@escaping (() -> ()), actionOnCancel: (() -> ())?)  {
        
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        let retryAction = UIAlertAction(title: Util.getString("Retry"), style: .default, handler : { (action) -> Void in
            actionOnRetry()
        })
        
        let cancelAction = UIAlertAction(title: Util.getString("Cancel"), style: .destructive, handler : { (action) -> Void in
            actionOnCancel?()
        })
        
        alertController.addAction(retryAction)
        alertController.addAction(cancelAction)
        
        viewController.present(alertController, animated: true, completion: nil)
    }
    
    static func AlertResend(viewController: UIViewController, title: String, message: String, actionOnRetry:@escaping (() -> ()), actionOnCancel: (() -> ())?)  {
        
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        let retryAction = UIAlertAction(title: Util.getString(Util.getString("resendEmail")), style: .default, handler : { (action) -> Void in
            actionOnRetry()
        })
        
        let cancelAction = UIAlertAction(title: Util.getString("OK"), style: .default, handler : { (action) -> Void in
            actionOnCancel?()
        })
        
        alertController.addAction(retryAction)
        alertController.addAction(cancelAction)
        
        viewController.present(alertController, animated: true, completion: nil)
    }
    
    static func AlertYesNo(viewController: UIViewController, title: String, message: String, actionYes:@escaping (() -> ()), actionNo:@escaping (() -> ()))  {
        
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        let retryAction = UIAlertAction(title: Util.getString("Yes"), style: .default, handler : { (action) -> Void in
            actionYes()
        })
        
        let cancelAction = UIAlertAction(title: Util.getString("No"), style: .default, handler : { (action) -> Void in
            actionNo()
        })
        
        alertController.addAction(retryAction)
        alertController.addAction(cancelAction)
        
        viewController.present(alertController, animated: true, completion: nil)
    }
    
    static func alertWithTwoActionsAndCancel(viewController: UIViewController, title: String, message: String, firstActionTitle: String, secondActionTitle: String, firstAction:@escaping (() -> ()), secondAction:@escaping (() -> ()))  {
        
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        let firstAction = UIAlertAction(title: Util.getString(firstActionTitle), style: .default, handler : { (action) -> Void in
            firstAction()
        })
        
        let secondAction = UIAlertAction(title: Util.getString(secondActionTitle), style: .default, handler : { (action) -> Void in
            secondAction()
        })
        
        let cancelAction = UIAlertAction(title: Util.getString("Cancel"), style: .default, handler : { (action) -> Void in
            return
        })
        
        alertController.addAction(firstAction)
        alertController.addAction(secondAction)
        alertController.addAction(cancelAction)
        
        viewController.present(alertController, animated: true, completion: nil)
    }
    
    static func alertWithTwoActions(viewController: UIViewController, title: String, message: String, firstActionTitle: String, secondActionTitle: String, firstAction:@escaping (() -> ()), secondAction:@escaping (() -> ()))  {
        
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        let firstAction = UIAlertAction(title: Util.getString(firstActionTitle), style: .default, handler : { (action) -> Void in
            firstAction()
        })
        
        let secondAction = UIAlertAction(title: Util.getString(secondActionTitle), style: .default, handler : { (action) -> Void in
            secondAction()
        })
        
        alertController.addAction(firstAction)
        alertController.addAction(secondAction)
        
        viewController.present(alertController, animated: true, completion: nil)
    }
    
    static func AlertWithOneActions(viewController: UIViewController, title: String, message: String, firstActionTitle: String, firstAction:@escaping (() -> ())){
        
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        let firstAction = UIAlertAction(title: Util.getString(firstActionTitle), style: .default, handler : { (action) -> Void in
            firstAction()
        })
        
        let cancelAction = UIAlertAction(title: Util.getString("Cancel"), style: .default, handler : { (action) -> Void in
            return
        })
        
        alertController.addAction(firstAction)
        alertController.addAction(cancelAction)
        
        viewController.present(alertController, animated: true, completion: nil)
    }
    
    static func AlertCameraNotFound(title: String, message: String, viewController: UIViewController){
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        let OKAction = UIAlertAction(title: "OK", style: .default, handler : { (action) -> Void in
            return
        })
        alertController.addAction(OKAction)
        viewController.present(alertController, animated: true, completion: nil)
    }

    
    static func getString(_ string: String) -> String{
        return NSLocalizedString(string, comment: "")
    }
    
    static func getTimeStringSince(_ dateTime: Date) -> String{
        var string = ""
        let calendar = NSCalendar.current
        // *** Get components using current Local & Timezone ***
        let createdTimeComponents = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: dateTime)
        let currentTimeComponents = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: Date())
        let yearsDifference = currentTimeComponents.year! - createdTimeComponents.year!
        let monthsDifference = currentTimeComponents.month! - createdTimeComponents.month!
        let daysDifference = currentTimeComponents.day! - createdTimeComponents.day!
        let hoursDifference = currentTimeComponents.hour! - createdTimeComponents.hour!
        let minutesDifference = currentTimeComponents.minute! - createdTimeComponents.minute!
        if yearsDifference > 0{
            if yearsDifference == 1{
                if monthsDifference < 0{
                    let monthsString = ((12 + monthsDifference) == 1) ? Util.getString("month") : Util.getString("months")
                    string = (12 + monthsDifference).description + " " + monthsString
                    
                    if daysDifference > 0{
                        let daysString = (daysDifference == 1) ? Util.getString("day") : Util.getString("days")
                        string += Util.getString(" and ") + daysDifference.description + " " + daysString
                    }
                    else if daysDifference < 0{
                        let daysString = ((31 + daysDifference) == 1) ? Util.getString("day") : Util.getString("days")
                        string += Util.getString(" and ") + (31 + daysDifference).description + " " + daysString
                    }

                }
                else{
                    string = yearsDifference.description + " " + Util.getString("year")
                    
                    if monthsDifference > 0{
                        let monthsString = (monthsDifference == 1) ? Util.getString("month") : Util.getString("months")
                        string += Util.getString(" and ") + monthsDifference.description + " " + monthsString
                    }
                }
            }
            else{
                string = yearsDifference.description + " " + Util.getString("years")
                
                if monthsDifference > 0{
                    let monthsString = (monthsDifference == 1) ? Util.getString("month") : Util.getString("months")
                    string += Util.getString(" and ") + monthsDifference.description + " " +  monthsString
                }
                    
                else if monthsDifference < 0{
                    let monthsString = ((12 + monthsDifference) == 1) ? Util.getString("month") : Util.getString("months")
                    string += Util.getString(" and ") + (12 + monthsDifference).description + " " + monthsString
                }
            }
        }
            
        else if monthsDifference > 0{
            if monthsDifference == 1{
                if daysDifference < 0{
                    let daysString = ((31 + daysDifference) == 1) ? Util.getString("day") : Util.getString("days")
                    string = (31 + daysDifference).description + " " + daysString
                    
                    if hoursDifference > 0{
                        let hoursString = (hoursDifference == 1) ? Util.getString("hour") : Util.getString("hours")
                        string += Util.getString(" and ") + hoursDifference.description + " " + hoursString
                    }
                    else if hoursDifference < 0{
                        let hoursString = ((24 + hoursDifference) == 1) ? Util.getString("hour") : Util.getString("hours")
                        string += Util.getString(" and ") + (24 + hoursDifference).description + " " + hoursString
                    }

                }
                else{
                    string = monthsDifference.description + " " + Util.getString("month")
                    if daysDifference > 0{
                        let daysString = (daysDifference == 1) ? Util.getString("day") : Util.getString("days")
                        string += Util.getString(" and ") + daysDifference.description + " " + daysString
                    }
                }
            }
            else{
                string = monthsDifference.description + " " + Util.getString("months")
                if daysDifference > 0{
                    let daysString = (daysDifference == 1) ? Util.getString("day") : Util.getString("days")
                    string += Util.getString(" and ") + daysDifference.description + " " + daysString
                }
                else if daysDifference < 0{
                    let daysString = ((31 + daysDifference) == 1) ? Util.getString("day") : Util.getString("days")
                    string += Util.getString(" and ") + (31 + daysDifference).description + " " + daysString
                }
            }
        }
            
        else if daysDifference > 0{
            if daysDifference == 1{
                if hoursDifference < 0{
                    let hoursString = ((24 + hoursDifference) == 1) ? Util.getString("hour") : Util.getString("hours")
                    string = (24 + hoursDifference).description + " " + hoursString
                    
                    if minutesDifference > 0{
                        let minutesString = (minutesDifference == 1) ? Util.getString("minute") : Util.getString("minutes")
                        string += Util.getString(" and ") + minutesDifference.description + " " + minutesString
                    }
                    else if minutesDifference < 0{
                        let minutesString = ((60 + minutesDifference) == 1) ? Util.getString("minute") : Util.getString("minutes")
                        string += Util.getString(" and ") + (60 + minutesDifference).description + " " + minutesString
                    }
                }
                else{
                    string = daysDifference.description + " " + Util.getString("day")
                    if hoursDifference > 0{
                        let hoursString = (hoursDifference == 1) ? Util.getString("hour") : Util.getString("hours")
                        string += Util.getString(" and ") + hoursDifference.description + " " + hoursString
                    }
                }
            }
            else{
                string = daysDifference.description + " " + Util.getString("days")
                if hoursDifference > 0{
                    let hoursString = (hoursDifference == 1) ? Util.getString("hour") : Util.getString("hours")
                    string += Util.getString(" and ") + hoursDifference.description + " " + hoursString
                }
                else if hoursDifference < 0{
                    let hoursString = ((24 + hoursDifference) == 1) ? Util.getString("hour") : Util.getString("hours")
                    string += Util.getString(" and ") + (24 + hoursDifference).description + " " + hoursString
                }
            }
        }
            
        else if hoursDifference > 0{
            if hoursDifference == 1{
                if minutesDifference < 0{
                    let minutesString = ((60 + minutesDifference) == 1) ? Util.getString("minute") : Util.getString("minutes")
                    string = (60 + minutesDifference).description + " " + minutesString
                }
                else{
                    string = hoursDifference.description + " " + Util.getString("hour")
                    if minutesDifference > 0{
                        let minutesString = (minutesDifference == 1) ? Util.getString("minute") : Util.getString("minutes")
                        string += Util.getString(" and ") + minutesDifference.description + " " + minutesString
                    }
                }
            }
            else{
                string = hoursDifference.description + " " + Util.getString("hours")
                if minutesDifference > 0{
                    let minutesString = (minutesDifference == 1) ? Util.getString("minute") : Util.getString("minutes")
                    string += Util.getString(" and ") + minutesDifference.description + " " + minutesString
                }
                else if minutesDifference < 0{
                    let minutesString = ((60 + minutesDifference) == 1) ? Util.getString("minute") : Util.getString("minutes")
                    string += Util.getString(" and ") + (60 + minutesDifference).description + " " + minutesString
                }
            }
        }
            
        else if minutesDifference >= 0{
            let minutesString = (minutesDifference <= 5) ? Util.getString("just now") : "\(minutesDifference) \(Util.getString("minutes"))"
            string = minutesString
        }
        if string != "just now"{
            string += " " + Util.getString("ago")
        }
        return string
    }
    
    static func decodeCurrencyId(currencyId: String) -> String{
        switch currencyId {
        case "EUR":
            return "€"
        case "USD":
            return "$"
        case "RON":
            return "RON"
        case "TRY":
            return "₺"
        default:
            return currencyId
        }
    }
    
    static func checkNumberOfDecimalPlaces(string: String) -> String{
        var isDotFound = false
        var dotPossition = 0
        var index = 0
        for char in string{
            if char == "."{
                dotPossition = index
                isDotFound = true
                break
            }
            index += 1
        }
        if (!isDotFound || (isDotFound && ((string.count - (dotPossition + 1)) <= 2))){
            return string
        }
        var newString = string
        newString.removeLast()
        return newString
    }
    
    static func checkNumberOfDecimalPlaces(string: String, digitCount: Int) -> String{
        var isDotFound = false
        var dotPossition = 0
        var index = 0
        for char in string{
            if char == "."{
                dotPossition = index
                isDotFound = true
                break
            }
            index += 1
        }
        if (!isDotFound || (isDotFound && ((string.count - (dotPossition + 1)) <= digitCount))){
            return string
        }
        var newString = string
        newString.removeLast()
        return newString
    }
    
    static func notifyWhenLabelTextWasChanged(label: UILabel){
        UIView.animate(withDuration: 1.0, delay: 0.5, options: [ .curveEaseInOut, .repeat], animations: {
            UIView.setAnimationRepeatCount(3)
            label.textColor = UIColor.red
            label.alpha = 0.0
            label.alpha = 1.0
        }, completion: { finished in
            label.textColor = UIColor.black
        })
    }
    
    static func notifyWhenTextWasChanged(textField: UITextField){
        UIView.animate(withDuration: 1.0, delay: 0.5, options: [ .curveEaseInOut, .repeat], animations: {
            UIView.setAnimationRepeatCount(3)
            textField.textColor = UIColor.red
            textField.alpha = 0.0
            textField.alpha = 1.0
        }, completion: { finished in
            textField.textColor = UIColor.black
        })
    }
    
    static func notifyWhenTextWasChanged(textField: UITextField, color: UIColor){
        UIView.animate(withDuration: 1.0, delay: 0.5, options: [ .curveEaseInOut, .repeat], animations: {
            UIView.setAnimationRepeatCount(3)
            textField.textColor = color
            textField.alpha = 0.0
            textField.alpha = 1.0
        }, completion: { finished in
            textField.textColor = UIColor.black
        })
    }
    
    static func notifyWhenButtonTextWasChanged(button: UIButton){
        UIView.animate(withDuration: 1.0, delay: 0.5, options: [ .curveEaseInOut, .repeat], animations: {
            UIView.setAnimationRepeatCount(2)
            button.setTitleColor(UIColor.red, for: .normal)
            button.alpha = 0.0
            button.alpha = 1.0
        }, completion: { finished in
            button.setTitleColor(UIColor.black, for: .normal)
        })
    }
    
    static func isTextDoubleValue(oldText: inout String, newText: String) -> Bool{
        var text = oldText
        text += newText
        if let _ = Double(text){
            let decimalCount = String(text).split(separator: ".")
            if decimalCount.count == 2{
                if decimalCount[1].count <= 2{
                    return true
                }
                return false
            }
            return true
        }
        return false
    }
    
    
    static func isTextDoubleValue(oldText: inout String, newText: String, location: Int, decimalPlaces: Int) -> Bool{
        var text: String = oldText
        text.insert(contentsOf: newText, at: text.index(text.startIndex, offsetBy: location))
        if let _ = Double(text){
            let decimalCount = String(text).split(separator: ".")
            if decimalCount.count == 2{
                if decimalCount[1].count <= decimalPlaces{
                    return true
                }
                return false
            }
            return true
        }
        return false
    }
    
    static func isTextDoubleValue(text: String, decimalPlaces: Int) -> Bool{
        if let _ = Double(text){
            let decimalCount = String(text).split(separator: ".")
            if decimalCount.count == 2{
                if decimalCount[1].count <= decimalPlaces{
                    return true
                }
                return false
            }
            return false
        }
        return false
    }
    
    static func isTextDoubleValue(value: String) -> Bool{
        if let _ = Double(value){
            let decimalCount = String(value).split(separator: ".")
            if decimalCount.count == 2{
                if decimalCount[1].count <= 2{
                    return true
                }
                return false
            }
            return true
        }
        return false
    }
    
    static func isTextIntegerValue(oldText: inout String, newText: String) -> Bool{
        var text = oldText
        text += newText
        if let number = Int(text){
            if number >= 0 {
                return true
            }
        }
        return false
    }
    
    static func simpleAlertWithTextEdit(title: String, message:String, UIViewController: UIViewController, actionYes: @escaping ((String?) -> ()), actionNo: @escaping (() -> ()))  {
        let alert = UIAlertController(title: Util.getString(title), message: Util.getString(message), preferredStyle: .alert)
        
        alert.addTextField { textField in
            let label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 22))
            label.textAlignment = NSTextAlignment.right
            label.textColor = UIColor(red: 0.78, green: 0.78, blue: 0.80, alpha: 1.0)
            textField.rightView = label
            textField.rightViewMode = .always
        }
        alert.addAction(UIAlertAction(title: Util.getString("Apply"), style: .default, handler: {(_) in
            actionYes(alert.textFields?[0].text)
        }))
        
        alert.addAction(UIAlertAction(title: Util.getString("Cancel"), style: .destructive, handler: {(_) in
            actionNo()
        }))
        
        UIViewController.present(alert, animated: true, completion: nil)
    }
    
    static func simpleAlertWithTextEdit(title: String, message:String, text: String, UIViewController: UIViewController, actionYes: @escaping ((String?) -> ()), actionNo: @escaping (() -> ()))  {
        let alert = UIAlertController(title: Util.getString(title), message: Util.getString(message), preferredStyle: .alert)
        
        alert.addTextField { textField in
            textField.text = text
        }
        alert.addAction(UIAlertAction(title: Util.getString("Apply"), style: .default, handler: {(_) in
           actionYes(alert.textFields?[0].text)
        }))
        
        alert.addAction(UIAlertAction(title: Util.getString("Cancel"), style: .destructive, handler: {(_) in
            actionNo()
        }))
        
        UIViewController.present(alert, animated: true, completion: nil)
    }
    
    static func simpleAlertWithTextEdit(title: String, message:String, text: String?, UIViewController: UIViewController, actionYes: @escaping ((String?) -> ()), actionNo: @escaping (() -> ()))  {
        let alert = UIAlertController(title: Util.getString(title), message: Util.getString(message), preferredStyle: .alert)
        
        alert.addTextField { textField in
            textField.text = text
            textField.keyboardType = .numbersAndPunctuation
        }
        alert.addAction(UIAlertAction(title: Util.getString("Apply"), style: .default, handler: {(_) in
            actionYes(alert.textFields?[0].text)
        }))
        
        alert.addAction(UIAlertAction(title: Util.getString("Cancel"), style: .destructive, handler: {(_) in
            actionNo()
        }))
        
        UIViewController.present(alert, animated: true, completion: {
            alert.textFields?[0].selectAll(alert)
        })
    }
    
    static func resizeImage(sourceImage:UIImage, newWidth: Int, newHeight: Int) -> UIImage{
        UIGraphicsBeginImageContext(CGSize(width:newWidth, height:newHeight))
        sourceImage.draw(in: CGRect(x:0, y:0, width:newWidth, height:newHeight))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return newImage!
    }
    
    static func resizeImage(sourceImage:UIImage, toWidth: CGFloat) -> UIImage {
        let newImage = sourceImage.resized(toWidth: toWidth)
        return newImage!
    }
    
    static func imageToBase64(image: UIImage) -> String{
        let imageData:NSData = image.pngData()! as NSData
        let imageStr = imageData.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
        return imageStr
    }
    
    static func getViewControllerFromStack(navigationController: UINavigationController?, viewController: UIViewController) -> UIViewController?{
        if let viewControllers = navigationController?.viewControllers{
            for vc in viewControllers{
                if vc.isKind(of: viewController.classForCoder){
                    return vc
                }
            }
        }
        return nil
    }
    
    static func isFidelityCardBarcode(barcode: String) -> Bool{
        if ((barcode.hasPrefix("040") && barcode.count == 13) || barcode.hasPrefix("123")){
            return true
        }
        return false
    }
    
    static func replaceSpecialCharacters(text: String) -> String {
        // replace the single quotes
        let text = text.replacingOccurrences(of: "'", with: "''")
            
        return text
    }
    
    static func writeLogCustom(eventName: String, name: String, text: String){
        Answers.logCustomEvent(withName: eventName, customAttributes: ["name": name, "full_text": "[\(settings.StoreId)][\(settings.CashRegister)]" + text])
    }
    
    static func writeLogLogin(method: String, success: NSNumber, customAttribute: [String:String]){
        Answers.logLogin(withMethod: method, success: success, customAttributes: customAttribute)
    }
    
    static func writeLogAddToCart(price: NSDecimalNumber, currency: String, itemName: String, itemType: String, itemId: String, customAttribute: [String:String]?){
        Answers.logAddToCart(withPrice: price, currency: currency, itemName: itemName, itemType: itemType, itemId: itemId, customAttributes: customAttribute)
    }
    
    static func writeLogStartCheckout(price: NSDecimalNumber, currency: String, itemCount: NSNumber, customAttribute: [String:String]?){
        Answers.logStartCheckout(withPrice: price, currency: currency, itemCount: itemCount, customAttributes: customAttribute)
    }
    
    static func writeLogPurchase(price: NSDecimalNumber, currency: String, succes: NSNumber, itemName: String, itemType: String, itemId: String, customAttribute: [String:String]?){
        Answers.logPurchase(withPrice: price, currency: currency, success: succes, itemName: itemName, itemType: itemType, itemId: itemId, customAttributes: customAttribute)
    }
    
    static func isOnlinePayment(paymentType: PaymentType) -> Bool {
        return paymentType.CategoryCode == PaymentCategory.EFT && paymentType.Code != PaymentTypeString.DCOFF && paymentType.Code != PaymentTypeString.CCOFF
    }
    
    static func getPropertyValue(key: String) -> String{
        var dictionary: NSDictionary? = nil
        if let path = Bundle.main.path(forResource: "Info", ofType: "plist"){
            dictionary = NSDictionary.init(contentsOfFile: path)
            if let dictionary = dictionary, let value = dictionary[key]{
                print("KEY: \(key) VALUE: \(value)")
                return value as! String
            }
        }
        return ""
    }
    
    static func applyDiscount(grossValue: Double, discountPercent: Double) -> Double{
        let discount = (grossValue * (1 - discountPercent)).rounded(toPlaces: 2)
        return discount
    }
    
    class Version{
        var version: String = String()
        var major: Int = 0
        var minor: Int = 0
        var build: Int = 0
        
        init(){
            
        }
        
        init(version: String){
            self.version = version
            let versionString = String(version).split(separator: ".")
            if versionString.count > 2{
                self.major = Int(versionString[0]) ?? 0
                self.minor = Int(versionString[1]) ?? 0
                self.build = Int(versionString[2]) ?? 0
            }
        }
        
        init(major: Int, minor: Int, build: Int) {
            self.major = major
            self.minor = minor
            self.build = build
        }
        
        static func >= (v1: Version, v2: Version) -> Bool{
            //Only major is important for backward compatibilities
            if(v1.major < v2.major){
                return false
            }
            return true
        }
    }
}
