<commit_before>//
//  FeedbackSlackViewController.swift
//  SlackTest
//
//  Created by <NAME> on 2016/08/21.
//  Copyright © 2016年 fromKK. All rights reserved.
//

import UIKit
import CoreTelephony

class FeedbackSlackViewController: UIViewController {
    @IBOutlet weak var topConstraint: NSLayoutConstraint!
    var defaultTopConstraint: CGFloat!
    @IBOutlet weak var closeButton: UIButton!
    var image: UIImage? {
        didSet {
            if self.isViewLoaded {
                self.imageView.image = image
            }
        }
    }
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var subjectField: FSSelectionField!
    @IBOutlet weak var commentView: FSTextView!
    @IBOutlet weak var indicatorView: UIView!

    lazy var transition: FS_Transition = FS_Transition()

    override func awakeFromNib() {
        super.awakeFromNib()

        self.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
        self.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        self.defaultTopConstraint = self.topConstraint.constant
        self.imageView.image = self.image

        if let subjects: [String] = FeedbackSlack.shared?.subjects {
            self.subjectField.items = subjects
        } else if let path: String = Bundle(for: type(of: self)).path(forResource: "FeedbackSlack", ofType: "plist"),
            let items: [String] = NSDictionary(contentsOfFile: path)?.object(forKey: "subjects") as? [String] {
            self.subjectField.items = items
        }

        self.commentView.layer.borderWidth = 1.0
        self.commentView.layer.borderColor = UIColor(white: 0.9, alpha: 1.0).cgColor
        self.commentView.layer.cornerRadius = 3.0

        let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.imageViewTapGestureRecognizer(_:)))
        self.imageView.addGestureRecognizer(tapGesture)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

        NotificationCenter.default.removeObserver(self)
    }

    @IBAction func closeButtonDidTapped(_ sender: AnyObject) {
        FeedbackSlack.shared?.close()
    }

    @IBAction func feedbackButtonDidTapped(_ sender: AnyObject) {
        let carrier: String = CTTelephonyNetworkInfo().subscriberCellularProvider?.carrierName ?? ""
        let reachability: Reachability = Reachability()!

        guard let subject: String = self.subjectField.selectedValue,
        let appName: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String,
        let version: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String,
        let build: String = Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as? String,
        let language: String = NSLocale.current.languageCode,
        let country: String = NSLocale.current.regionCode
        else {
            return
        }

        let comment: String = self.commentView.text ?? ""
        let border: String = "------------------------"

        var posts: [[String]] = [
            ["内容", subject],
            ["コメント", comment],
            [border],
            ["アプリ名", appName],
            ["アプリバージョン", version],
            ["ビルド番号", build],
            ["端末名", UIDevice.current.name],
            ["モデル", UIDevice.current.model],
            ["OS名", UIDevice.current.systemName],
            ["iOSバージョン", UIDevice.current.systemVersion],
            ["言語", language],
            ["国", country],
            ["ネットワーク環境", reachability.currentReachabilityStatus.description],
            ["キャリア名", carrier]
        ]

        if let options = FeedbackSlack.shared?.options {
            posts += [
                [border],
                ["オプション", options]
            ]
        }

        let post: String = posts.map { (post: [String]) -> String in
            post.joined(separator: ": ")
            }.joined(separator: "\n")
        self.postSlack(post)
    }

    fileprivate func postSlack(_ comment: String) {
        guard let slack: FeedbackSlack = FeedbackSlack.shared,
            let image: UIImage = self.image,
            let data: Data = UIImagePNGRepresentation(image),
            let appName: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String
            else {
            return
        }

        let dateFormatter: DateFormatter = DateFormatter()
        dateFormatter.locale = NSLocale.current
        dateFormatter.timeZone = NSTimeZone.local
        dateFormatter.dateFormat = "yyyy/MM/dd HH:mm:ss"
        let date: String = dateFormatter.string(from: Date())

        let fileUpload: FileUpload = FileUpload(token: slack.slackToken, data: data, filename: "\(Date().timeIntervalSince1970).png", contentType: "image/png", title: "\(appName) feedback \(date)", initialComment: comment, channels: [slack.slackChannel])

        self.indicatorView.isHidden = false
        let configration: URLSessionConfiguration = URLSessionConfiguration.default
        let session: URLSession = URLSession(configuration: configration)
        let task: URLSessionTask = session.dataTask(with: fileUpload.request) { [weak self] (data: Data?, response: URLResponse?, error: Error?) in
            if let data = data {
                do {
                    guard let json: [String: AnyObject] = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: AnyObject] else {
                        fatalError("json serialization failed")
                    }
                    if json["ok"] as? Int == 1 {
                        FeedbackSlack.shared?.close()
                    }
                } catch {
                    print("json serialization failed")
                }

            } else if let error = error {
                print("error:\(error)")
            }

            self?.indicatorView.isHidden = true
        }
        task.resume()
    }
}

extension FeedbackSlackViewController {
    func keyboardWillShow(_ notification: Notification) {<commit_msg>bugfix: take too long time feedback finish<commit_after>//
//  FeedbackSlackViewController.swift
//  SlackTest
//
//  Created by <NAME> on 2016/08/21.
//  Copyright © 2016年 fromKK. All rights reserved.
//

import UIKit
import CoreTelephony

class FeedbackSlackViewController: UIViewController {
    @IBOutlet weak var topConstraint: NSLayoutConstraint!
    var defaultTopConstraint: CGFloat!
    @IBOutlet weak var closeButton: UIButton!
    var image: UIImage? {
        didSet {
            if self.isViewLoaded {
                self.imageView.image = image
            }
        }
    }
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var subjectField: FSSelectionField!
    @IBOutlet weak var commentView: FSTextView!
    @IBOutlet weak var indicatorView: UIView!

    lazy var transition: FS_Transition = FS_Transition()

    override func awakeFromNib() {
        super.awakeFromNib()

        self.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
        self.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        self.defaultTopConstraint = self.topConstraint.constant
        self.imageView.image = self.image

        if let subjects: [String] = FeedbackSlack.shared?.subjects {
            self.subjectField.items = subjects
        } else if let path: String = Bundle(for: type(of: self)).path(forResource: "FeedbackSlack", ofType: "plist"),
            let items: [String] = NSDictionary(contentsOfFile: path)?.object(forKey: "subjects") as? [String] {
            self.subjectField.items = items
        }

        self.commentView.layer.borderWidth = 1.0
        self.commentView.layer.borderColor = UIColor(white: 0.9, alpha: 1.0).cgColor
        self.commentView.layer.cornerRadius = 3.0

        let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.imageViewTapGestureRecognizer(_:)))
        self.imageView.addGestureRecognizer(tapGesture)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

        NotificationCenter.default.removeObserver(self)
    }

    @IBAction func closeButtonDidTapped(_ sender: AnyObject) {
        FeedbackSlack.shared?.close()
    }

    @IBAction func feedbackButtonDidTapped(_ sender: AnyObject) {
        self.commentView.resignFirstResponder()

        let carrier: String = CTTelephonyNetworkInfo().subscriberCellularProvider?.carrierName ?? ""
        let reachability: Reachability = Reachability()!

        guard let subject: String = self.subjectField.selectedValue,
        let appName: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String,
        let version: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String,
        let build: String = Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as? String,
        let language: String = NSLocale.current.languageCode,
        let country: String = NSLocale.current.regionCode
        else {
            return
        }

        let comment: String = self.commentView.text ?? ""
        let border: String = "------------------------"

        var posts: [[String]] = [
            ["内容", subject],
            ["コメント", comment],
            [border],
            ["アプリ名", appName],
            ["アプリバージョン", version],
            ["ビルド番号", build],
            ["端末名", UIDevice.current.name],
            ["モデル", UIDevice.current.model],
            ["OS名", UIDevice.current.systemName],
            ["iOSバージョン", UIDevice.current.systemVersion],
            ["言語", language],
            ["国", country],
            ["ネットワーク環境", reachability.currentReachabilityStatus.description],
            ["キャリア名", carrier]
        ]

        if let options = FeedbackSlack.shared?.options {
            posts += [
                [border],
                ["オプション", options]
            ]
        }

        let post: String = posts.map { (post: [String]) -> String in
            post.joined(separator: ": ")
            }.joined(separator: "\n")
        self.postSlack(post)
    }

    fileprivate func postSlack(_ comment: String) {
        guard let slack: FeedbackSlack = FeedbackSlack.shared,
            let image: UIImage = self.image,
            let data: Data = UIImagePNGRepresentation(image),
            let appName: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String
            else {
            return
        }

        let dateFormatter: DateFormatter = DateFormatter()
        dateFormatter.locale = NSLocale.current
        dateFormatter.timeZone = NSTimeZone.local
        dateFormatter.dateFormat = "yyyy/MM/dd HH:mm:ss"
        let date: String = dateFormatter.string(from: Date())

        let fileUpload: FileUpload = FileUpload(token: slack.slackToken, data: data, filename: "\(Date().timeIntervalSince1970).png", contentType: "image/png", title: "\(appName) feedback \(date)", initialComment: comment, channels: [slack.slackChannel])

        self.indicatorView.isHidden = false
        let configration: URLSessionConfiguration = URLSessionConfiguration.default
        let session: URLSession = URLSession(configuration: configration)
        let task: URLSessionTask = session.dataTask(with: fileUpload.request) { [weak self] (data: Data?, response: URLResponse?, error: Error?) in
            DispatchQueue.main.async {
                if let data = data {
                    do {
                        guard let json: [String: AnyObject] = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: AnyObject] else {
                            fatalError("json serialization failed")
                        }
                        if json["ok"] as? Int == 1 {
                            FeedbackSlack.shared?.close()
                        }
                    } catch {
                        print("json serialization failed")
                    }

                } else if let error = error {
                    print("error:\(error)")
                }
                
                self?.indicatorView.isHidden = true
            }
        }
        task.resume()
    }
}

extension FeedbackSlackViewController {
    func keyboardWillShow(_ notification: Notification) {
{'fraction_non_alphanumeric': 0.10538432974378018, 'fraction_numerical': 0.003713330857779428, 'mean_word_length': 2.421239837398374, 'pattern_counts': {'":': 2, '<': 5, '<?xml version=': 0, '>': 7, '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': '6201591', 'n_tokens_mistral': 3834, 'n_tokens_neox': 3635, 'n_words': 816}