<commit_before>//
//  LogoLoader.swift
//  Client
//
//  Created by Sahakyan on 1/2/17.
//  Copyright © 2017 Mozilla. All rights reserved.
//

import Foundation
import Alamofire
import SnapKit
import WebImage
import SwiftyJSON

struct LogoInfo {
	var url: String?
	var color: String?
	var prefix: String?
	var fontSize: Int?
	var hostName: String?
}

extension String {

	func asciiValue() -> Int {
		var s = UInt32(0)
		for ch in self.unicodeScalars {
			if ch.isASCII {
				s += ch.value
			}
		}
		return Int(s)
	}
}

class LogoLoader {

	private static let dbVersion = "1502005705085"
    private static let dispatchQueue = DispatchQueue(label: "com.cliqz.logoLoader", attributes: .concurrent);

	private static var _logoDB: JSON?
	private static var logoDB: JSON? {
		get {
			if self._logoDB == nil {
				if let path = Bundle.main.path(forResource: "logo-database", ofType: "json", inDirectory: "Extension/build/mobile/search/core"),
				   let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe) as Data {
					self._logoDB = JSON(jsonData)
				}
			}
			return self._logoDB
		}
		set {
			self._logoDB = newValue
		}
	}

	class func loadLogo(_ url: String, completionBlock: @escaping (_ image: UIImage?, _ logoInfo: LogoInfo?,  _ error: Error?) -> Void) {
        dispatchQueue.async {
            let details = LogoLoader.fetchLogoDetails(url)
            if let u = details.url {
                LogoLoader.downloadImage(u, completed: { (image, error) in
                    DispatchQueue.main.async {
                        completionBlock(image, details, error)
                    }
                })
            } else {
                DispatchQueue.main.async {
                    completionBlock(nil, details, nil)
                }
            }
        }
	}

	class func clearDB() {
		self.logoDB = nil
	}

	private class func fetchLogoDetails(_ url: String) -> LogoInfo {
		var logoDetails = LogoInfo()
		logoDetails.color = nil
		logoDetails.fontSize = 16
		if let urlDetails = URLParser.getURLDetails(url),
		   let hostName = urlDetails.name,
		   let details = self.logoDB?["domains"][hostName] {
			logoDetails.hostName = hostName
			logoDetails.prefix = hostName.substring(to: hostName.index(hostName.startIndex, offsetBy: min(2, hostName.characters.count))).capitalized
			if let list = details.array,
				list.count > 0 {
				for info in list {
					if info != JSON.null,
					   let r = info["r"].string,
					   isMatchingLogoRule(urlDetails, r) || info == list.last {

						if let doesLogoExist = info["l"].number, doesLogoExist == 1 {
							logoDetails.url = "https://cdn.cliqz.com/brands-database/database/\(self.dbVersion)/pngs/\(hostName)/\(r)_192.png"
						}
						logoDetails.color = info["b"].string
						if let txt = info["t"].string {
							logoDetails.prefix = txt
						}
						break
					}
				}
			}<commit_msg>Bad hack to fix a bug in URL parser, till we integrate another lib<commit_after>//
//  LogoLoader.swift
//  Client
//
//  Created by Sahakyan on 1/2/17.
//  Copyright © 2017 Mozilla. All rights reserved.
//

import Foundation
import Alamofire
import SnapKit
import WebImage
import SwiftyJSON

struct LogoInfo {
	var url: String?
	var color: String?
	var prefix: String?
	var fontSize: Int?
	var hostName: String?
}

extension String {

	func asciiValue() -> Int {
		var s = UInt32(0)
		for ch in self.unicodeScalars {
			if ch.isASCII {
				s += ch.value
			}
		}
		return Int(s)
	}
}

class LogoLoader {

	private static let dbVersion = "1502005705085"
    private static let dispatchQueue = DispatchQueue(label: "com.cliqz.logoLoader", attributes: .concurrent);

	private static var _logoDB: JSON?
	private static var logoDB: JSON? {
		get {
			if self._logoDB == nil {
				if let path = Bundle.main.path(forResource: "logo-database", ofType: "json", inDirectory: "Extension/build/mobile/search/core"),
				   let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe) as Data {
					self._logoDB = JSON(jsonData)
				}
			}
			return self._logoDB
		}
		set {
			self._logoDB = newValue
		}
	}

	class func loadLogo(_ url: String, completionBlock: @escaping (_ image: UIImage?, _ logoInfo: LogoInfo?,  _ error: Error?) -> Void) {
        dispatchQueue.async {
            let details = LogoLoader.fetchLogoDetails(url)
            if let u = details.url {
                LogoLoader.downloadImage(u, completed: { (image, error) in
                    DispatchQueue.main.async {
                        completionBlock(image, details, error)
                    }
                })
            } else {
                DispatchQueue.main.async {
                    completionBlock(nil, details, nil)
                }
            }
        }
	}

	class func clearDB() {
		self.logoDB = nil
	}

	private class func fetchLogoDetails(_ url: String) -> LogoInfo {
		var logoDetails = LogoInfo()
		logoDetails.color = nil
		logoDetails.fontSize = 16
		var fixedURL = url
		// TODO: Remove this crazy hack, which is done for localNews. For the next release we should change url parsing lib to https://publicsuffix.org/learn/
		if url.contains("tz.de") {
			fixedURL = "http://tz.de"
		}
		if let urlDetails = URLParser.getURLDetails(fixedURL),
		   let hostName = urlDetails.name,
		   let details = self.logoDB?["domains"][hostName] {
			logoDetails.hostName = hostName
			logoDetails.prefix = hostName.substring(to: hostName.index(hostName.startIndex, offsetBy: min(2, hostName.characters.count))).capitalized
			if let list = details.array,
				list.count > 0 {
				for info in list {
					if info != JSON.null,
					   let r = info["r"].string,
					   isMatchingLogoRule(urlDetails, r) || info == list.last {

						if let doesLogoExist = info["l"].number, doesLogoExist == 1 {
							logoDetails.url = "https://cdn.cliqz.com/brands-database/database/\(self.dbVersion)/pngs/\(hostName)/\(r)_192.png"
						}
						logoDetails.color = info["b"].string
						if let txt = info["t"].string {
							logoDetails.prefix = txt
						}
						break
					}
				}
			}
{'fraction_non_alphanumeric': 0.1137035819914558, 'fraction_numerical': 0.010515938218862965, 'mean_word_length': 2.502301495972382, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 11, 'https://': 3, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2758179', 'n_tokens_mistral': 2255, 'n_tokens_neox': 1897, 'n_words': 492}