<commit_before>
import UIKit

class InputHistoryTableViewController: UITableViewController {

    var rows: [[NSObject: AnyObject]] = []
    /*
    override init() {
        super.init(style: UITableViewStyle.Plain)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // Need this to prevent runtime error:
    // fatal error: use of unimplemented initializer 'init(nibName:bundle:)'
    // for class 'TestViewController'
    // I made this private since users should use the no-argument constructor.
    private override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
*/
    
    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.registerNib(UINib(nibName: "InputHistoryRowCell", bundle: nil), forCellReuseIdentifier: "inputHistoryRowCell")
        
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
        
        let documentsFolder = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
        let databasePath = documentsFolder.stringByAppendingPathComponent("history.sqlite")
        
        let databaseQueue = FMDatabaseQueue(path: databasePath)
        
        if databaseQueue == nil {
            println("Unable to open database")
            return
        }
        
        databaseQueue?.inDatabase() {
            db in
            if let rs = db.executeQuery("select candidate, shuangpin, shengmu, length, frequency, candidate_type from history", withArgumentsInArray: nil) {
                while rs.next() {
                    self.rows.append(rs.resultDictionary())
                }
            } else {
                println("select failed: \(db.lastErrorMessage())")
            }
        }
        
        databaseQueue!.close()
        
        self.rows.sort {
            ($0["frequency"] as NSNumber).integerValue > ($1["frequency"] as NSNumber).integerValue
        }
    }

    // MARK: - Table view data source

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return rows.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("inputHistoryRowCell", forIndexPath: indexPath) as InputHistoryRowCell

        let row = rows[indexPath.row]
        cell.candidateLabel.text = (row["candidate"] as String)
        cell.shuangpinLabel.text = (row["shuangpin"] as String)
        cell.shengmuLabel.text = (row["shengmu"] as String)
        cell.lengthLabel.text = String((row["length"] as NSNumber).integerValue)
        cell.frequencyLabel.text = String((row["frequency"] as NSNumber).integerValue)
        switch (row["candidate_type"] as NSNumber).integerValue {
        case 1:
            cell.typeLabel.text = "中"
        case 2:
            cell.typeLabel.text = "英"
        case 3:
            cell.typeLabel.text = "符"
        default:
            assertionFailure("Wrong candidate type in history.sqlite")
        }
        
        return cell
    }

    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {<commit_msg>Change: InputHistoryTableView only show input history not in candidates.sqlite<commit_after>
import UIKit

class InputHistoryTableViewController: UITableViewController {

    var rows: [[NSObject: AnyObject]] = []
    /*
    override init() {
        super.init(style: UITableViewStyle.Plain)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // Need this to prevent runtime error:
    // fatal error: use of unimplemented initializer 'init(nibName:bundle:)'
    // for class 'TestViewController'
    // I made this private since users should use the no-argument constructor.
    private override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
*/
    
    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.registerNib(UINib(nibName: "InputHistoryRowCell", bundle: nil), forCellReuseIdentifier: "inputHistoryRowCell")
        
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
        
        let documentsFolder = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
        let databasePath = documentsFolder.stringByAppendingPathComponent("history.sqlite")
        
        let databaseQueue = FMDatabaseQueue(path: databasePath)
        
        if databaseQueue == nil {
            println("Unable to open database")
            return
        }
        
        databaseQueue?.inDatabase() {
            db in
            if let rs = db.executeQuery("select candidate, shuangpin, shengmu, length, frequency, candidate_type from history", withArgumentsInArray: nil) {
                while rs.next() {
                    self.rows.append(rs.resultDictionary())
                }
            } else {
                println("select failed: \(db.lastErrorMessage())")
            }
        }
        
        databaseQueue!.close()
        
        self.rows.sort {
            ($0["frequency"] as NSNumber).integerValue > ($1["frequency"] as NSNumber).integerValue
        }
        
        self.rows = self.rows.filter {
            self.candidateTextIsInCandidatesDatabase($0["candidate"] as String) == false
        }
    }

    // MARK: - Table view data source

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return rows.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("inputHistoryRowCell", forIndexPath: indexPath) as InputHistoryRowCell

        let row = rows[indexPath.row]
        cell.candidateLabel.text = (row["candidate"] as String)
        cell.shuangpinLabel.text = (row["shuangpin"] as String)
        cell.shengmuLabel.text = (row["shengmu"] as String)
        cell.lengthLabel.text = String((row["length"] as NSNumber).integerValue)
        cell.frequencyLabel.text = String((row["frequency"] as NSNumber).integerValue)
        switch (row["candidate_type"] as NSNumber).integerValue {
        case 1:
            cell.typeLabel.text = "中"
        case 2:
            cell.typeLabel.text = "英"
        case 3:
            cell.typeLabel.text = "符"
        default:
            assertionFailure("Wrong candidate type in history.sqlite")
        }
        
        return cell
    }
    
    lazy var _candidateDatabase: FMDatabase = {
        let databasePath = NSBundle.mainBundle().pathForResource("candidates", ofType: "sqlite")
        let database = FMDatabase(path: databasePath)
        if !database.open() {
            assertionFailure("Unable to open database")
        }
        return database
    }()
    
    func candidateTextIsInCandidatesDatabase(candidateText: String) -> Bool {
        if let rs = _candidateDatabase.executeQuery("select * from candidates where candidate == ?", withArgumentsInArray: [candidateText]) {
            if rs.next() {
                return true
            } else {
                return false
            }
        } else {
            assertionFailure("select failed: \(_candidateDatabase.lastErrorMessage())")
        }
    }
    
    deinit {
        _candidateDatabase.close()
    }

    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
{'fraction_non_alphanumeric': 0.09265816808309726, 'fraction_numerical': 0.001534466477809254, 'mean_word_length': 2.476815757078375, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 12, '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': '4257313', 'n_tokens_mistral': 2309, 'n_tokens_neox': 2211, 'n_words': 562}