<commit_before>//
//  InternalCacheDB.swift
//  iAsync_cache
//
//  Created by <NAME> on 13.08.14.
//  Copyright (c) 2014 EmbeddedSources. All rights reserved.
//

import Foundation

import iAsync_restkit
import iAsync_utils
import iAsync_reactiveKit

import ReactiveKit

private var autoremoveSchedulersByCacheName: [String:Timer] = [:]

private let internalCacheDBLockObject = NSObject()

//TODO should be private?
final internal class InternalCacheDB : KeyValueDB, CacheDB {

    let cacheDBInfo: CacheDBInfo

    init(cacheDBInfo: CacheDBInfo) {

        self.cacheDBInfo = cacheDBInfo

        super.init(cacheFileName:cacheDBInfo.fileName)
    }

    private func removeOldData() {

        let removeRarelyAccessDataDelay = cacheDBInfo.autoRemoveByLastAccessDate

        if removeRarelyAccessDataDelay > 0.0 {

            let fromDate = NSDate().dateByAddingTimeInterval(-removeRarelyAccessDataDelay)

            removeRecordsToAccessDate(fromDate)
        }

        let bytes = Int64(cacheDBInfo.autoRemoveByMaxSizeInMB) * 1024 * 1024

        if bytes > 0 {
            removeRecordsWhileTotalSizeMoreThenBytes(bytes)
        }
    }

    func runAutoRemoveDataSchedulerIfNeeds() {

        synced(internalCacheDBLockObject, { () -> () in

            if autoremoveSchedulersByCacheName[self.cacheDBInfo.dbPropertyName] != nil {
                return
            }

            let timer = Timer()
            autoremoveSchedulersByCacheName[self.cacheDBInfo.dbPropertyName] = timer

            let block = { (cancel: SimpleBlock) -> () in

                let loadDataBlock = { (progress: AnyObject -> Void) -> Result<Void, NSError> in

                    self.removeOldData()
                    return .Success(())
                }

                let queueName = "com.embedded_sources.dbcache.thread_to_remove_old_data"
                asyncStreamWithJob(queueName, job: loadDataBlock).on(failure: { error -> () in
                    error.writeErrorWithLogger()
                }).run()
            }
            block({})

            let _ = timer.addBlock(block, duration:3600.0, leeway:1800.0)
        })
    }

    //JTODO check using of migrateDB method when multithreaded
    func migrateDB(dbInfo: DBInfo) {

        let currentDbInfo = dbInfo.currentDbVersionsByName
        let currVersionNum   = currentDbInfo?[cacheDBInfo.dbPropertyName] as? NSNumber

        guard let currVersionNum_ = currVersionNum else { return }

        let lastVersion    = cacheDBInfo.version
        let currentVersion = currVersionNum_.integerValue

        if lastVersion > currentVersion {
            removeAllRecordsWithCallback(nil)
        }
    }
}
<commit_msg>refactor with using of reactiveKit<commit_after>//
//  InternalCacheDB.swift
//  iAsync_cache
//
//  Created by <NAME> on 13.08.14.
//  Copyright (c) 2014 EmbeddedSources. All rights reserved.
//

import Foundation

import iAsync_restkit
import iAsync_utils
import iAsync_reactiveKit

import ReactiveKit

private var autoremoveSchedulersByCacheName: [String:Timer] = [:]

private let internalCacheDBLockObject = NSObject()

//TODO should be private?
final internal class InternalCacheDB : KeyValueDB, CacheDB {

    let cacheDBInfo: CacheDBInfo

    init(cacheDBInfo: CacheDBInfo) {

        self.cacheDBInfo = cacheDBInfo

        super.init(cacheFileName:cacheDBInfo.fileName)
    }

    private func removeOldData() {

        let removeRarelyAccessDataDelay = cacheDBInfo.autoRemoveByLastAccessDate

        if removeRarelyAccessDataDelay > 0.0 {

            let fromDate = NSDate().dateByAddingTimeInterval(-removeRarelyAccessDataDelay)

            removeRecordsToAccessDate(fromDate)
        }

        let bytes = Int64(cacheDBInfo.autoRemoveByMaxSizeInMB) * 1024 * 1024

        if bytes > 0 {
            removeRecordsWhileTotalSizeMoreThenBytes(bytes)
        }
    }

    func runAutoRemoveDataSchedulerIfNeeds() {

        synced(internalCacheDBLockObject, { () -> () in

            if autoremoveSchedulersByCacheName[self.cacheDBInfo.dbPropertyName] != nil {
                return
            }

            let timer = Timer()
            autoremoveSchedulersByCacheName[self.cacheDBInfo.dbPropertyName] = timer

            let block = { (cancel: SimpleBlock) -> () in

                let loadDataBlock = { (progress: AnyObject -> Void) -> Result<Void, NSError> in

                    self.removeOldData()
                    return .Success(())
                }

                let queueName = "com.embedded_sources.dbcache.thread_to_remove_old_data"
                asyncStreamWithJob(queueName, job: loadDataBlock).on(failure: { error -> () in
                    error.writeErrorWithLogger()
                }).run()
            }
            block({})

            let _ = timer.addBlock(block, duration:3600.0, leeway:1800.0)
        })
    }

    func migrateDB(dbInfo: DBInfo) {

        let currentDbInfo  = dbInfo.currentDbVersionsByName
        let currVersionNum = currentDbInfo?[cacheDBInfo.dbPropertyName] as? NSNumber

        guard let currVersionNum_ = currVersionNum else { return }

        let lastVersion    = cacheDBInfo.version
        let currentVersion = currVersionNum_.integerValue

        if lastVersion > currentVersion {
            removeAllRecordsWithCallback(nil)
        }
    }
}

{'fraction_non_alphanumeric': 0.08118774666416087, 'fraction_numerical': 0.01240368351813569, 'mean_word_length': 2.381194409148666, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 23, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6190502', 'n_tokens_mistral': 1580, 'n_tokens_neox': 1469, 'n_words': 300}