<commit_before>//
//  MassController.swift
//  MyWeight
//
//  Created by <NAME> on 10/7/16.
//  Copyright © 2016 <NAME>. All rights reserved.
//

import Foundation
import HealthKit

public protocol HealthStoreProtocol {

    func requestAuthorization(toShare typesToShare: Set<HKSampleType>?,
                              read typesToRead: Set<HKObjectType>?,
                              completion: @escaping (Bool, Error?) -> Void)

    func earliestPermittedSampleDate() -> Date

    func execute(_ query: HKQuery)

    func save(_ object: HKObject, withCompletion completion: @escaping (Bool, Error?) -> Void)

    func authorizationStatusForType(_ type: HKObjectType) -> HKAuthorizationStatus
    static func isHealthDataAvailable() -> Bool

}

extension HKHealthStore: HealthStoreProtocol {}


public class MassController {

    let healthStore: HealthStoreProtocol
    let bodyMass: HKQuantityTypeIdentifier
    let massType: HKQuantityType

    public init(healthStore: HealthStoreProtocol = HKHealthStore()) {
        self.healthStore = healthStore
        self.bodyMass = HKQuantityTypeIdentifier.bodyMass
        // I don't like this `!`
        self.massType = HKObjectType.quantityType(forIdentifier: self.bodyMass)!
    }

    public func requestAuthorization(_ completion: @escaping (_ error: Error?) -> Void ) {

        let massSet = Set<HKSampleType>(arrayLiteral: massType)

        healthStore.requestAuthorization(toShare: massSet, read: massSet) { (success, error) in
            DispatchQueue.main.async {
                completion(error)
            }
        }
    }

    public func fetch(_ completion: @escaping (_ results: [Mass]) -> Void) {
        let startDate = healthStore.earliestPermittedSampleDate()
        let endDate = Date()

        let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: HKQueryOptions())
        let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false)

        let query = HKSampleQuery(sampleType: massType,
                                  predicate: predicate,
                                  limit: HKObjectQueryNoLimit,
                                  sortDescriptors: [sortDescriptor])
        { query, results, error in
            // WARNING: improve
            guard error == nil else {
                Log.debug(error)

                return
            }

            guard let samples = results as? [HKQuantitySample] else {
                fatalError("An error occured fetching the user's tracked food. In your app, try to handle this error gracefully. The error was: \(error?.localizedDescription)")
            }

            if samples.isEmpty {
                Log.debug("No samples")
            }

            let masses = samples.map { Mass(with: $0) }

            DispatchQueue.main.async {
                completion(masses)
            }
        }

        healthStore.execute(query)
    }

    public func save(_ mass: Mass,
                     completion: @escaping (_ error: Error?) -> Void)
    {
        let quantity = HKQuantity(unit: .gramUnit(with: .kilo),
                                  doubleValue: mass.value.converted(to: .kilograms).value)

        let metadata = [HKMetadataKeyWasUserEntered: true]<commit_msg>Fixes Log.debug warning on MassController.swift (#67)<commit_after>//
//  MassController.swift
//  MyWeight
//
//  Created by <NAME> on 10/7/16.
//  Copyright © 2016 <NAME>. All rights reserved.
//

import Foundation
import HealthKit

public protocol HealthStoreProtocol {

    func requestAuthorization(toShare typesToShare: Set<HKSampleType>?,
                              read typesToRead: Set<HKObjectType>?,
                              completion: @escaping (Bool, Error?) -> Void)

    func earliestPermittedSampleDate() -> Date

    func execute(_ query: HKQuery)

    func save(_ object: HKObject, withCompletion completion: @escaping (Bool, Error?) -> Void)

    func authorizationStatusForType(_ type: HKObjectType) -> HKAuthorizationStatus
    static func isHealthDataAvailable() -> Bool

}

extension HKHealthStore: HealthStoreProtocol {}


public class MassController {

    let healthStore: HealthStoreProtocol
    let bodyMass: HKQuantityTypeIdentifier
    let massType: HKQuantityType

    public init(healthStore: HealthStoreProtocol = HKHealthStore()) {
        self.healthStore = healthStore
        self.bodyMass = HKQuantityTypeIdentifier.bodyMass
        // I don't like this `!`
        self.massType = HKObjectType.quantityType(forIdentifier: self.bodyMass)!
    }

    public func requestAuthorization(_ completion: @escaping (_ error: Error?) -> Void ) {

        let massSet = Set<HKSampleType>(arrayLiteral: massType)

        healthStore.requestAuthorization(toShare: massSet, read: massSet) { (success, error) in
            DispatchQueue.main.async {
                completion(error)
            }
        }
    }

    public func fetch(_ completion: @escaping (_ results: [Mass]) -> Void) {
        let startDate = healthStore.earliestPermittedSampleDate()
        let endDate = Date()

        let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: HKQueryOptions())
        let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false)

        let query = HKSampleQuery(sampleType: massType,
                                  predicate: predicate,
                                  limit: HKObjectQueryNoLimit,
                                  sortDescriptors: [sortDescriptor])
        { query, results, error in
            // WARNING: improve
            guard error == nil else {
                Log.debug(error as Any)

                return
            }

            guard let samples = results as? [HKQuantitySample] else {
                fatalError("An error occured fetching the user's tracked food. In your app, try to handle this error gracefully. The error was: \(error?.localizedDescription)")
            }

            if samples.isEmpty {
                Log.debug("No samples")
            }

            let masses = samples.map { Mass(with: $0) }

            DispatchQueue.main.async {
                completion(masses)
            }
        }

        healthStore.execute(query)
    }

    public func save(_ mass: Mass,
                     completion: @escaping (_ error: Error?) -> Void)
    {
        let quantity = HKQuantity(unit: .gramUnit(with: .kilo),
                                  doubleValue: mass.value.converted(to: .kilograms).value)

        let metadata = [HKMetadataKeyWasUserEntered: true]
{'fraction_non_alphanumeric': 0.08814223293656773, 'fraction_numerical': 0.0033147506403495555, 'mean_word_length': 2.185220729366603, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 29, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6512941', 'n_tokens_mistral': 1810, 'n_tokens_neox': 1641, 'n_words': 452}