<commit_before>//
//  LanguageSettingsViewController.swift
//  KeymanEngine
//
//  Created by <NAME> on 5/29/19.
//  Copyright © 2019 SIL International. All rights reserved.
//

import UIKit

private let toolbarButtonTag = 100

class LanguageSettingsViewController: UITableViewController {
  let language: Language
  private var settingsArray = [[String: String]]()
  private var keyboardRepository: KeyboardRepository?

  private var doPredictionsSwitch: UISwitch?
  private var doCorrectionsSwitch: UISwitch?
  private var doCorrectionsLabel: UILabel?
  private var correctionsCell: UITableViewCell?

  public init(_ keyboardRepository: KeyboardRepository?, _ inLanguage: Language) {
    language = inLanguage
    self.keyboardRepository = keyboardRepository
    super.init(nibName: nil, bundle: nil)
  }
  
  required public init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

  open override func loadView() {
    super.loadView()
    tableView?.delegate = self
  }
  
  override func viewDidLoad() {
    super.viewDidLoad()
    title = "\(language.name) Settings"
    log.info("viewDidLoad: LanguageSettingsViewController title: \(title ?? "<empty>")")

    if Manager.shared.canAddNewKeyboards {
      let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self,
                                      action: #selector(self.addClicked))
      navigationItem.rightBarButtonItem = addButton
    }
  }
  
  override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    log.info("didAppear: LanguageSettingsViewController")
  }
  
  
  // MARK: - Table view data source UITableViewDataSource

  override func numberOfSections(in tableView: UITableView) -> Int {
      return 2
  }

  override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if 0 == section {
      // so far as I know, there is always at least one keyboard or else we won't show
      let kbct = language.keyboards!.count
      return kbct
    } else {
      return 3  // 4 in future when we can manage a user dictionary
    }
  }
  
  public func frameAtRightOfCell(cell cellFrame: CGRect, controlSize: CGSize) -> CGRect {
    let rightOffset = cellFrame.size.width
    let switchWidth: CGFloat = 20
    let switchX = rightOffset - switchWidth
    let switchHeight = controlSize.height
    let cellSwitchHeightDiff = cellFrame.size.height - switchHeight
    let switchY = cellFrame.origin.y + 0.5 * cellSwitchHeightDiff
    
    let switchFrame = CGRect(x: switchX,
                             y: switchY,
                             width: switchWidth,
                             height: cellFrame.size.height)
    return switchFrame
  }
  
  @objc
  func predictionSwitchValueChanged(source: UISwitch) {
    let value = source.isOn;
    let userDefaults = Storage.active.userDefaults
    userDefaults.set(predictSetting: value, forLanguageID: self.language.id)

    // Reactively set the corrections switch interactivity state.
    self.doCorrectionsSwitch?.isHidden = !value
    self.doCorrectionsLabel?.isEnabled = value
    self.correctionsCell?.isUserInteractionEnabled = value
    
    if let lm = Manager.shared.preferredLexicalModel(userDefaults, forLanguage: self.language.id) {
      if Manager.shared.currentKeyboardID?.languageID == self.language.id {
        // re-register the model - that'll enact the settings.
        _ = Manager.shared.registerLexicalModel(lm)
      }
    }
  }
  
  @objc
  func correctionSwitchValueChanged(source: UISwitch) {
    let value = source.isOn;
    let userDefaults = Storage.active.userDefaults
    userDefaults.set(correctSetting: value, forLanguageID: self.language.id)
    
    if let lm = Manager.shared.preferredLexicalModel(userDefaults, forLanguage: self.language.id) {
      if Manager.shared.currentKeyboardID?.languageID == self.language.id {
        // re-register the model - that'll enact the settings.
        _ = Manager.shared.registerLexicalModel(lm)
      }
    }
  }

  override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let userDefaults = Storage.active.userDefaults
    
    let cellIdentifier = 0 == indexPath.section ?  "KeyboardInLanguageSettingsCell" : "LanguageSettingsCell"
    
    let reusableCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
    if let cell = reusableCell {
      return cell<commit_msg>fix(ios): Predict/correct toggles act immediately<commit_after>//
//  LanguageSettingsViewController.swift
//  KeymanEngine
//
//  Created by <NAME> on 5/29/19.
//  Copyright © 2019 SIL International. All rights reserved.
//

import UIKit

private let toolbarButtonTag = 100

class LanguageSettingsViewController: UITableViewController {
  let language: Language
  private var settingsArray = [[String: String]]()
  private var keyboardRepository: KeyboardRepository?

  private var doPredictionsSwitch: UISwitch?
  private var doCorrectionsSwitch: UISwitch?
  private var doCorrectionsLabel: UILabel?
  private var correctionsCell: UITableViewCell?

  public init(_ keyboardRepository: KeyboardRepository?, _ inLanguage: Language) {
    language = inLanguage
    self.keyboardRepository = keyboardRepository
    super.init(nibName: nil, bundle: nil)
  }
  
  required public init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

  open override func loadView() {
    super.loadView()
    tableView?.delegate = self
  }
  
  override func viewDidLoad() {
    super.viewDidLoad()
    title = "\(language.name) Settings"
    log.info("viewDidLoad: LanguageSettingsViewController title: \(title ?? "<empty>")")

    if Manager.shared.canAddNewKeyboards {
      let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self,
                                      action: #selector(self.addClicked))
      navigationItem.rightBarButtonItem = addButton
    }
  }
  
  override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    log.info("didAppear: LanguageSettingsViewController")
  }
  
  
  // MARK: - Table view data source UITableViewDataSource

  override func numberOfSections(in tableView: UITableView) -> Int {
      return 2
  }

  override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if 0 == section {
      // so far as I know, there is always at least one keyboard or else we won't show
      let kbct = language.keyboards!.count
      return kbct
    } else {
      return 3  // 4 in future when we can manage a user dictionary
    }
  }
  
  public func frameAtRightOfCell(cell cellFrame: CGRect, controlSize: CGSize) -> CGRect {
    let rightOffset = cellFrame.size.width
    let switchWidth: CGFloat = 20
    let switchX = rightOffset - switchWidth
    let switchHeight = controlSize.height
    let cellSwitchHeightDiff = cellFrame.size.height - switchHeight
    let switchY = cellFrame.origin.y + 0.5 * cellSwitchHeightDiff
    
    let switchFrame = CGRect(x: switchX,
                             y: switchY,
                             width: switchWidth,
                             height: cellFrame.size.height)
    return switchFrame
  }
  
  @objc
  func predictionSwitchValueChanged(source: UISwitch) {
    let value = source.isOn;
    let userDefaults = Storage.active.userDefaults
    userDefaults.set(predictSetting: value, forLanguageID: self.language.id)

    // Reactively set the corrections switch interactivity state.
    self.doCorrectionsSwitch?.isHidden = !value
    self.doCorrectionsLabel?.isEnabled = value
    self.correctionsCell?.isUserInteractionEnabled = value
    
    if let lm = Manager.shared.preferredLexicalModel(userDefaults, forLanguage: self.language.id) {
      if Manager.shared.currentKeyboardID?.languageID == self.language.id {
        // re-register the model - that'll enact the settings.
        _ = Manager.shared.registerLexicalModel(lm)
      }
      // Based on how Manager chooses the model in setKeyboard.
    } else if let lm = userDefaults.userLexicalModels?.first(where: { $0.languageID == self.language.id }) {
      if Manager.shared.currentKeyboardID?.languageID == self.language.id {
        _ = Manager.shared.registerLexicalModel(lm)
      }
    }
  }
  
  @objc
  func correctionSwitchValueChanged(source: UISwitch) {
    let value = source.isOn;
    let userDefaults = Storage.active.userDefaults
    userDefaults.set(correctSetting: value, forLanguageID: self.language.id)
    
    if let lm = Manager.shared.preferredLexicalModel(userDefaults, forLanguage: self.language.id) {
      if Manager.shared.currentKeyboardID?.languageID == self.language.id {
        // re-register the model - that'll enact the settings.
        _ = Manager.shared.registerLexicalModel(lm)
      }
      // Based on how Manager chooses the model in setKeyboard.
    } else if let lm = userDefaults.userLexicalModels?.first(where: { $0.languageID == self.language.id }) {
      if Manager.shared.currentKeyboardID?.languageID == self.language.id {
        _ = Manager.shared.registerLexicalModel(lm)
      }
    }
  }

  override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let userDefaults = Storage.active.userDefaults
    
    let cellIdentifier = 0 == indexPath.section ?  "KeyboardInLanguageSettingsCell" : "LanguageSettingsCell"
    
    let reusableCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
    if let cell = reusableCell {
      return cell
{'fraction_non_alphanumeric': 0.08612040133779264, 'fraction_numerical': 0.00459866220735786, 'mean_word_length': 3.171316477768091, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 15, 'https://': 0, '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': '2896604', 'n_tokens_mistral': 2820, 'n_tokens_neox': 2659, 'n_words': 689}