<commit_before>//
//  StepCounter.swift
//  2200
//
//  Created by <NAME> on 2/4/15.
//  Copyright (c) 2015 <NAME>. All rights reserved.
//

import Foundation

import HealthKit

class StepCounter {
  
  var healthStore : HKHealthStore;
  
  var stepCount : Int {
    didSet{
      self.delegate.countUpdated(stepCount)
    }
  }
  
  var delegate : CountDelegate;
  
  init(healthStore : HKHealthStore, delegate : CountDelegate){
    
    self.healthStore = healthStore
    
    self.stepCount = 0;
    self.delegate = delegate
    
    healthStore.requestAuthorizationToShareTypes(nil, readTypes: dataTypesToRead(), completion: {
      (success:Bool, error:NSError!) -> Void in
//      if !success{
//        var alert = UIAlertView(title: "Missed authorization", message: "The app cannot work without authorization for HealthKit. Closing", delegate: nil, cancelButtonTitle: nil, otherButtonTitles: "Close")
//        alert.show();
//        self.dismissViewControllerAnimated(true, completion: nil)
        
//      }
      if success {
        
        println("Permission acquired")
        
        self.initStepCount()
        
      }
    })
   
  }
  
  private func initStepCount(){
    
    let past : NSDate = NSDate.distantPast() as NSDate
    let now = NSDate()
    
    let mostRecentPredicate = HKQuery.predicateForSamplesWithStartDate(past, endDate: now, options: HKQueryOptions.None)
    
    let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false);
    
    let idSteps = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)
    
    let statQuery = HKStatisticsQuery(quantityType: idSteps, quantitySamplePredicate: mostRecentPredicate, options: HKStatisticsOptions.CumulativeSum, completionHandler: {(_,statistics,_) -> Void in
      if (statistics != nil) {
        
        var source : HKSource = statistics.sources.first as HKSource
        println("Number of sources: \(statistics.sources.count)")
        if let quantity : HKQuantity! = statistics.sumQuantity(){
          self.stepCount = Int(quantity.doubleValueForUnit(HKUnit(fromString: "count")));
        }
        
      }
    })
    
    
    healthStore.executeQuery(statQuery);
  }
  
  
  private func dataTypesToRead() -> NSSet {
    
    var typeIds = [HKQuantityTypeIdentifierHeight, HKQuantityTypeIdentifierBodyMass, HKQuantityTypeIdentifierDistanceWalkingRunning]
    
    
//    var type1 = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)
//    var type2 = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)<commit_msg>Counting from 24 hours ago.<commit_after>//
//  StepCounter.swift
//  2200
//
//  Created by <NAME> on 2/4/15.
//  Copyright (c) 2015 <NAME>. All rights reserved.
//

import Foundation

import HealthKit

class StepCounter {
  
  var healthStore : HKHealthStore;
  
  var stepCount : Int {
    didSet{
      self.delegate.countUpdated(stepCount)
    }
  }
  
  var delegate : CountDelegate;
  
  init(healthStore : HKHealthStore, delegate : CountDelegate){
    
    self.healthStore = healthStore
    
    self.stepCount = 0;
    self.delegate = delegate
    
    healthStore.requestAuthorizationToShareTypes(nil, readTypes: dataTypesToRead(), completion: {
      (success:Bool, error:NSError!) -> Void in
//      if !success{
//        var alert = UIAlertView(title: "Missed authorization", message: "The app cannot work without authorization for HealthKit. Closing", delegate: nil, cancelButtonTitle: nil, otherButtonTitles: "Close")
//        alert.show();
//        self.dismissViewControllerAnimated(true, completion: nil)
        
//      }
      if success {
        
        println("Permission acquired")
        
        self.initStepCount()
        
      }
    })
   
  }
  
  private func initStepCount(){
    
    let past : NSDate = NSDate.distantPast() as NSDate
    
    let yesterday = NSDate(timeIntervalSinceNow: -24*60*60)
    
    let now = NSDate()
    
    let mostRecentPredicate = HKQuery.predicateForSamplesWithStartDate(yesterday, endDate: now, options: HKQueryOptions.StrictStartDate)
    
    let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false);
    
    let idSteps = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)
    
    let statQuery = HKStatisticsQuery(quantityType: idSteps, quantitySamplePredicate: mostRecentPredicate, options: HKStatisticsOptions.CumulativeSum, completionHandler: {(_,statistics,_) -> Void in
      if (statistics != nil) {
        
        var source : HKSource = statistics.sources.first as HKSource
        println("Number of sources: \(statistics.sources.count)")
        if let quantity : HKQuantity! = statistics.sumQuantity(){
          self.stepCount = Int(quantity.doubleValueForUnit(HKUnit(fromString: "count")));
        }
        
      }
    })
    
    
    healthStore.executeQuery(statQuery);
  }
  
  
  private func dataTypesToRead() -> NSSet {
    
    var typeIds = [HKQuantityTypeIdentifierHeight, HKQuantityTypeIdentifierBodyMass, HKQuantityTypeIdentifierDistanceWalkingRunning]
    
    
//    var type1 = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)
//    var type2 = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)
{'fraction_non_alphanumeric': 0.09305816135084428, 'fraction_numerical': 0.007129455909943715, 'mean_word_length': 3.069465648854962, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 13, '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': '316455', 'n_tokens_mistral': 1613, 'n_tokens_neox': 1504, 'n_words': 327}