<commit_before>//
//  SJEditorViewController.swift
//  SwiftyJSONAccelerator
//
//  Created by Karthik on 16/10/2015.
//  Copyright © 2015 <NAME>. All rights reserved.
//

import Cocoa
import SwiftyJSON

fileprivate func < <T: Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l < r
  case (nil, _?):
    return true
  default:
    return false
  }
}

fileprivate func <= <T: Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l <= r
  default:
    return !(rhs < lhs)
  }
}


/// View for the processing of the content and generation of the files.
class SJEditorViewController: NSViewController, NSTextViewDelegate {

  // MARK: Outlet files.
  @IBOutlet var textView: SJTextView!
  @IBOutlet var messageLabel: NSTextField!
  @IBOutlet var errorImageView: NSImageView!
  @IBOutlet var baseClassTextField: NSTextField!
  @IBOutlet var prefixClassTextField: NSTextField!
  @IBOutlet var companyNameTextField: NSTextField!
  @IBOutlet var authorNameTextField: NSTextField!
  @IBOutlet var includeHeaderImportCheckbox: NSButton!
  @IBOutlet var enableNSCodingSupportCheckbox: NSButton!
  @IBOutlet var librarySelector: NSPopUpButton!
  @IBOutlet var modelTypeSelectorSegment: NSSegmentedControl!

  // MARK: View methods
  override func loadView() {
    super.loadView()
    textView!.delegate = self
    textView!.updateFormat()
    textView!.lnv_setUpLineNumberView()
    resetErrorImage()
    authorNameTextField?.stringValue = NSFullUserName()
  }

  // MARK: Actions
  @IBAction func format(_ sender: AnyObject?) {
    if validateAndFormat(true) {
      generateModel()
    }

  }

  /**
   Validates and updates the textview.

   - parameter pretty: If the JSON is to be pretty printed.

   - returns: if the format was valid.
   */
  func validateAndFormat(_ pretty: Bool) -> Bool {

    if textView?.string?.characters.count == 0 {
      return false
    }

    textView!.updateFormat()
    let (valid, error): (Bool, NSError?) = JSONHelper.isStringValidJSON(textView?.string)
      if valid {
        if pretty {
          textView?.string = JSONHelper.prettyJSON(textView?.string)!
          textView!.lnv_textDidChange(Notification.init(name: NSNotification.Name.NSTextDidChange, object: nil))
          return true
        }
        correctJSONMessage()
      } else if error != nil {
        handleError(error)
        textView!.lnv_textDidChange(Notification.init(name: NSNotification.Name.NSTextDidChange, object: nil))
        return false
      } else {
        genericJSONError()
    }
    return false
  }

  /**
   Actual function that generates the model.
   */
  func generateModel() {

    // The base class field is blank, cannot proceed without it.
    // Possibly can have a default value in the future.
    if baseClassTextField?.stringValue.characters.count <= 0 {
      let alert = NSAlert()
      alert.messageText = "Enter a base class name to continue."
      alert.runModal()
      return
    }

    let filePath = openFile()

    // No file path was selected, go back!
    if filePath == nil {
      return
    }

    let object: AnyObject? = JSONHelper.convertToObject(textView?.string).1

    // Checks for validity of the content, else can cause crashes.
    if object != nil {

        let nsCodingState = self.enableNSCodingSupportCheckbox.state == 1 && (modelTypeSelectorSegment.selectedSegment == 1)
        let constructType = self.modelTypeSelectorSegment.selectedSegment == 0 ? ConstructType.ClassType : ConstructType.StructType
        let libraryType = self.librarySelector.indexOfSelectedItem == 0 ? JSONMappingLibrary.SwiftyJSON : JSONMappingLibrary.ObjectMapper
        let configuration = ModelGenerationConfiguration.init(
            filePath: filePath!.appending("/"),
            baseClassName: baseClassTextField.stringValue,
            authorName: authorNameTextField.stringValue,
            companyName: companyNameTextField.stringValue,
            prefix: prefixClassTextField.stringValue,
            constructType: constructType,
            modelMappingLibrary: libraryType,
            supportNSCoding: nsCodingState)
        let modelGenerator = ModelGenerator.init(JSON(object!), configuration)
        let filesGenerated = modelGenerator.generate()
        var successState = true
        for file in filesGenerated {
            let content = FileGenerator.generateFileContentWith(file, configuration: configuration)
            let name = file.fileName
            let path = configuration.filePath
            successState = FileGenerator.writeToFileWith(name, content: content, path: path)
        }
        notify(completionState: successState, fileCount: filesGenerated.count)
    } else {
      let alert: NSAlert = NSAlert()
      alert.messageText = "Unable to save the file check the content."
      alert.runModal()
    }
  }

  @IBAction func recalcEnabledBoxes(_ sender: AnyObject) {
    self.enableNSCodingSupportCheckbox.isEnabled = (modelTypeSelectorSegment.selectedSegment == 1)
  }


    func notify(completionState: Bool, fileCount: Int) {
        let notification = NSUserNotification()
        notification.title = "SwiftyJSONAccelerator"
        if completionState && fileCount > 0 {
            notification.subtitle = "Completed - \(fileCount) Generated."
        } else {
            notification.subtitle = "No files were generated, cannot model arrays inside arrays."
        }
        NSUserNotificationCenter.default.deliver(notification)
    }

  // MARK: Internal Methods

  /**
   Get the line number, column and the character for the position in the given string.

   - parameters:
   - string: The JSON string that is in the textview.
   - position: the location where the error is.

   - returns:
   - character: the string that was causing the issue.
   - line: the linenumber where the error was.
   - column: the column where the error was.
   */
  func characterRowAndLineAt(_ string: String, position: Int)
    -> (character: String, line: Int, column: Int) {
      var lineNumber = 0<commit_msg>switched the struct and class generation options<commit_after>//
//  SJEditorViewController.swift
//  SwiftyJSONAccelerator
//
//  Created by Karthik on 16/10/2015.
//  Copyright © 2015 <NAME>. All rights reserved.
//

import Cocoa
import SwiftyJSON

fileprivate func < <T: Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l < r
  case (nil, _?):
    return true
  default:
    return false
  }
}

fileprivate func <= <T: Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l <= r
  default:
    return !(rhs < lhs)
  }
}


/// View for the processing of the content and generation of the files.
class SJEditorViewController: NSViewController, NSTextViewDelegate {

  // MARK: Outlet files.
  @IBOutlet var textView: SJTextView!
  @IBOutlet var messageLabel: NSTextField!
  @IBOutlet var errorImageView: NSImageView!
  @IBOutlet var baseClassTextField: NSTextField!
  @IBOutlet var prefixClassTextField: NSTextField!
  @IBOutlet var companyNameTextField: NSTextField!
  @IBOutlet var authorNameTextField: NSTextField!
  @IBOutlet var includeHeaderImportCheckbox: NSButton!
  @IBOutlet var enableNSCodingSupportCheckbox: NSButton!
  @IBOutlet var librarySelector: NSPopUpButton!
  @IBOutlet var modelTypeSelectorSegment: NSSegmentedControl!

  // MARK: View methods
  override func loadView() {
    super.loadView()
    textView!.delegate = self
    textView!.updateFormat()
    textView!.lnv_setUpLineNumberView()
    resetErrorImage()
    authorNameTextField?.stringValue = NSFullUserName()
  }

  // MARK: Actions
  @IBAction func format(_ sender: AnyObject?) {
    if validateAndFormat(true) {
      generateModel()
    }

  }

  /**
   Validates and updates the textview.

   - parameter pretty: If the JSON is to be pretty printed.

   - returns: if the format was valid.
   */
  func validateAndFormat(_ pretty: Bool) -> Bool {

    if textView?.string?.characters.count == 0 {
      return false
    }

    textView!.updateFormat()
    let (valid, error): (Bool, NSError?) = JSONHelper.isStringValidJSON(textView?.string)
      if valid {
        if pretty {
          textView?.string = JSONHelper.prettyJSON(textView?.string)!
          textView!.lnv_textDidChange(Notification.init(name: NSNotification.Name.NSTextDidChange, object: nil))
          return true
        }
        correctJSONMessage()
      } else if error != nil {
        handleError(error)
        textView!.lnv_textDidChange(Notification.init(name: NSNotification.Name.NSTextDidChange, object: nil))
        return false
      } else {
        genericJSONError()
    }
    return false
  }

  /**
   Actual function that generates the model.
   */
  func generateModel() {

    // The base class field is blank, cannot proceed without it.
    // Possibly can have a default value in the future.
    if baseClassTextField?.stringValue.characters.count <= 0 {
      let alert = NSAlert()
      alert.messageText = "Enter a base class name to continue."
      alert.runModal()
      return
    }

    let filePath = openFile()

    // No file path was selected, go back!
    if filePath == nil {
      return
    }

    let object: AnyObject? = JSONHelper.convertToObject(textView?.string).1

    // Checks for validity of the content, else can cause crashes.
    if object != nil {

        let nsCodingState = self.enableNSCodingSupportCheckbox.state == 1 && (modelTypeSelectorSegment.selectedSegment == 1)
        let constructType = self.modelTypeSelectorSegment.selectedSegment == 0 ? ConstructType.StructType : ConstructType.ClassType
        let libraryType = self.librarySelector.indexOfSelectedItem == 0 ? JSONMappingLibrary.SwiftyJSON : JSONMappingLibrary.ObjectMapper
        let configuration = ModelGenerationConfiguration.init(
            filePath: filePath!.appending("/"),
            baseClassName: baseClassTextField.stringValue,
            authorName: authorNameTextField.stringValue,
            companyName: companyNameTextField.stringValue,
            prefix: prefixClassTextField.stringValue,
            constructType: constructType,
            modelMappingLibrary: libraryType,
            supportNSCoding: nsCodingState)
        let modelGenerator = ModelGenerator.init(JSON(object!), configuration)
        let filesGenerated = modelGenerator.generate()
        var successState = true
        for file in filesGenerated {
            let content = FileGenerator.generateFileContentWith(file, configuration: configuration)
            let name = file.fileName
            let path = configuration.filePath
            successState = FileGenerator.writeToFileWith(name, content: content, path: path)
        }
        notify(completionState: successState, fileCount: filesGenerated.count)
    } else {
      let alert: NSAlert = NSAlert()
      alert.messageText = "Unable to save the file check the content."
      alert.runModal()
    }
  }

  @IBAction func recalcEnabledBoxes(_ sender: AnyObject) {
    self.enableNSCodingSupportCheckbox.isEnabled = (modelTypeSelectorSegment.selectedSegment == 1)
  }


    func notify(completionState: Bool, fileCount: Int) {
        let notification = NSUserNotification()
        notification.title = "SwiftyJSONAccelerator"
        if completionState && fileCount > 0 {
            notification.subtitle = "Completed - \(fileCount) Files Generated"
        } else {
            notification.subtitle = "No files were generated, cannot model arrays inside arrays."
        }
        NSUserNotificationCenter.default.deliver(notification)
    }

  // MARK: Internal Methods

  /**
   Get the line number, column and the character for the position in the given string.

   - parameters:
   - string: The JSON string that is in the textview.
   - position: the location where the error is.

   - returns:
   - character: the string that was causing the issue.
   - line: the linenumber where the error was.
   - column: the column where the error was.
   */
  func characterRowAndLineAt(_ string: String, position: Int)
    -> (character: String, line: Int, column: Int) {
      var lineNumber = 0
{'fraction_non_alphanumeric': 0.09029142108709888, 'fraction_numerical': 0.003601833660772757, 'mean_word_length': 2.983371372676883, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 19, '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': '5102816', 'n_tokens_mistral': 3495, 'n_tokens_neox': 3340, 'n_words': 992}