<commit_before>//
//  MessageFetchingOperation.swift
//
//  Created by <NAME>. on 20/06/16.
//

import Foundation
import CoreData

final class MessageFetchingOperation: Operation {
	let context: NSManagedObjectContext
	let finishBlock: ((MessagesSyncResult) -> Void)?
	var result = MessagesSyncResult.Cancel
	
	init(context: NSManagedObjectContext, finishBlock: ((MessagesSyncResult) -> Void)? = nil) {
		self.context = context
		self.finishBlock = finishBlock
		
		super.init()
	}
	
	override func execute() {
		MMLogDebug("[Message fetching] Starting operation...")
		self.syncMessages()
	}
	
	private func syncMessages() {
		guard let internalId = MobileMessaging.currentUser?.internalId else
		{
			self.finishWithError(NSError(type: MMInternalErrorType.NoRegistration))
			return
		}
		
		self.context.performAndWait {
			let date = NSDate(timeIntervalSinceNow: -60 * 60 * 24 * 7) // consider messages not older than 7 days
			let fetchLimit = 100 // consider 100 most recent messages
			let nonReportedMessages = MessageManagedObject.MM_findAllWithPredicate(NSPredicate(format: "reportSent == false"), context: self.context)
			let archivedMessages = MessageManagedObject.MM_find(withPredicate: NSPredicate(format: "reportSent == true && creationDate > %@", date), fetchLimit: fetchLimit, sortedBy: "creationDate", ascending: false, inContext: self.context)
			
			let nonReportedMessageIds = nonReportedMessages?.map{ $0.messageId }
			let archveMessageIds = archivedMessages?.map{ $0.messageId }
			
			MMLogDebug("Found \(nonReportedMessageIds?.count) not reported messages. \(archivedMessages?.count) archive messages.")
			
			MobileMessaging.sharedInstance?.remoteApiManager.syncMessages(internalId: internalId, archiveMsgIds: archveMessageIds, dlrMsgIds: nonReportedMessageIds) { result in
				self.handleRequestResponse(result: result, nonReportedMessageIds: nonReportedMessageIds)
			}
		}
	}

	private func handleRequestResponse(result: MessagesSyncResult, nonReportedMessageIds: [String]?) {
		self.result = result
		
		self.context.performAndWait {
			switch result {
			case .Success(let fetchResponse):
				let fetchedMessages = fetchResponse.messages
				MMLogDebug("[Message fetching] succeded: received \(fetchedMessages?.count) new messages: \(fetchedMessages)")
				
				if let nonReportedMessageIds = nonReportedMessageIds {
					self.dequeueDeliveryReports(messageIDs: nonReportedMessageIds)
					MMLogDebug("[Message fetching] delivery report sent for messages: \(nonReportedMessageIds)")
					if !nonReportedMessageIds.isEmpty {
						NotificationCenter.mm_postNotificationFromMainThread(name: MMNotificationDeliveryReportSent, userInfo: [MMNotificationKeyDLRMessageIDs: nonReportedMessageIds])
					}
				}
				
			case .Failure(_):
				MMLogError("[Message fetching] request failed")
			case .Cancel:
				MMLogDebug("[Message fetching] cancelled")
			}
		}
		self.finishWithError(result.error as NSError?)
	}
	
	private func dequeueDeliveryReports(messageIDs: [String]) {
		guard let messages = MessageManagedObject.MM_findAllWithPredicate(NSPredicate(format: "messageId IN %@", messageIDs), context: context)<commit_msg>Refines logging<commit_after>//
//  MessageFetchingOperation.swift
//
//  Created by <NAME>. on 20/06/16.
//

import Foundation
import CoreData

final class MessageFetchingOperation: Operation {
	let context: NSManagedObjectContext
	let finishBlock: ((MessagesSyncResult) -> Void)?
	var result = MessagesSyncResult.Cancel
	
	init(context: NSManagedObjectContext, finishBlock: ((MessagesSyncResult) -> Void)? = nil) {
		self.context = context
		self.finishBlock = finishBlock
		
		super.init()
	}
	
	override func execute() {
		MMLogDebug("[Message fetching] Starting operation...")
		self.syncMessages()
	}
	
	private func syncMessages() {
		guard let internalId = MobileMessaging.currentUser?.internalId else
		{
			self.finishWithError(NSError(type: MMInternalErrorType.NoRegistration))
			return
		}
		
		self.context.performAndWait {
			let date = NSDate(timeIntervalSinceNow: -60 * 60 * 24 * 7) // consider messages not older than 7 days
			let fetchLimit = 100 // consider 100 most recent messages
			let nonReportedMessages = MessageManagedObject.MM_findAllWithPredicate(NSPredicate(format: "reportSent == false"), context: self.context)
			let archivedMessages = MessageManagedObject.MM_find(withPredicate: NSPredicate(format: "reportSent == true && creationDate > %@", date), fetchLimit: fetchLimit, sortedBy: "creationDate", ascending: false, inContext: self.context)
			
			let nonReportedMessageIds = nonReportedMessages?.map{ $0.messageId }
			let archveMessageIds = archivedMessages?.map{ $0.messageId }
			
			MMLogDebug("Found \(nonReportedMessageIds?.count) not reported messages. \(archivedMessages?.count) archive messages.")
			
			MobileMessaging.sharedInstance?.remoteApiManager.syncMessages(internalId: internalId, archiveMsgIds: archveMessageIds, dlrMsgIds: nonReportedMessageIds) { result in
				self.handleRequestResponse(result: result, nonReportedMessageIds: nonReportedMessageIds)
			}
		}
	}

	private func handleRequestResponse(result: MessagesSyncResult, nonReportedMessageIds: [String]?) {
		self.result = result
		
		self.context.performAndWait {
			switch result {
			case .Success(let fetchResponse):
				let fetchedMessages = fetchResponse.messages
				MMLogDebug("[Message fetching] succeded: received \(fetchedMessages?.count)")
				
				if let nonReportedMessageIds = nonReportedMessageIds {
					self.dequeueDeliveryReports(messageIDs: nonReportedMessageIds)
					MMLogDebug("[Message fetching] delivery report sent for messages: \(nonReportedMessageIds)")
					if !nonReportedMessageIds.isEmpty {
						NotificationCenter.mm_postNotificationFromMainThread(name: MMNotificationDeliveryReportSent, userInfo: [MMNotificationKeyDLRMessageIDs: nonReportedMessageIds])
					}
				}
				
			case .Failure(_):
				MMLogError("[Message fetching] request failed")
			case .Cancel:
				MMLogDebug("[Message fetching] cancelled")
			}
		}
		self.finishWithError(result.error as NSError?)
	}
	
	private func dequeueDeliveryReports(messageIDs: [String]) {
		guard let messages = MessageManagedObject.MM_findAllWithPredicate(NSPredicate(format: "messageId IN %@", messageIDs), context: context)
{'fraction_non_alphanumeric': 0.09819862904511398, 'fraction_numerical': 0.007014187788936713, 'mean_word_length': 5.067698259187621, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 11, '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': '3436417', 'n_tokens_mistral': 2056, 'n_tokens_neox': 1773, 'n_words': 401}