<commit_before>//
//  RegisterPickAvatarViewController.swift
//  Yep
//
//  Created by NIX on 15/3/18.
//  Copyright (c) 2015年 Catch Inc. All rights reserved.
//

import UIKit
import AVFoundation
import Photos

class RegisterPickAvatarViewController: UIViewController {
    
    @IBOutlet weak var avatarImageView: UIImageView!
    @IBOutlet weak var cameraPreviewView: CameraPreviewView!

    @IBOutlet weak var takePicturePromptLabel: UILabel!

    @IBOutlet weak var openCameraButton: BorderButton!

    @IBOutlet weak var cameraRollButton: UIButton!
    @IBOutlet weak var captureButton: UIButton!
    @IBOutlet weak var retakeButton: UIButton!

    lazy var nextButton: UIBarButtonItem = {
        let button = UIBarButtonItem(title: NSLocalizedString("Next", comment: ""), style: .Plain, target: self, action: "next:")
        return button
        }()

    var avatar = UIImage() {
        willSet {
            avatarImageView.image = newValue
        }
    }

    enum PickAvatarState {
        case Default
        case CameraOpen
        case Captured
    }

    var pickAvatarState: PickAvatarState = .Default {
        willSet {
            switch newValue {
            case .Default:
                openCameraButton.hidden = false

                cameraRollButton.hidden = true
                captureButton.hidden = true
                retakeButton.hidden = true

                cameraPreviewView.hidden = true
                avatarImageView.hidden = false

                avatarImageView.image = UIImage(named: "default_avatar")

                nextButton.enabled = false

            case .CameraOpen:
                openCameraButton.hidden = true

                cameraRollButton.hidden = false
                captureButton.hidden = false
                retakeButton.hidden = true

                cameraPreviewView.hidden = false
                avatarImageView.hidden = false

                captureButton.setImage(UIImage(named: "button_capture"), forState: .Normal)

                nextButton.enabled = false

            case .Captured:
                openCameraButton.hidden = true

                cameraRollButton.hidden = false
                captureButton.hidden = false
                retakeButton.hidden = false

                cameraPreviewView.hidden = true
                avatarImageView.hidden = false

                captureButton.setImage(UIImage(named: "button_capture_ok"), forState: .Normal)

                nextButton.enabled = true
            }
        }
    }

    lazy var sessionQueue = {
        return dispatch_queue_create("session queue", DISPATCH_QUEUE_SERIAL)
        }()

    lazy var session: AVCaptureSession = {
        let _session = AVCaptureSession()
        _session.sessionPreset = AVCaptureSessionPreset640x480

        return _session
        }()

    let mediaType = AVMediaTypeVideo

    lazy var videoDeviceInput: AVCaptureDeviceInput = {
        var error: NSError? = nil
        let videoDevice = self.deviceWithMediaType(self.mediaType, preferringPosition: .Front)
        return AVCaptureDeviceInput(device: videoDevice!, error: &error)
        }()

    lazy var stillImageOutput: AVCaptureStillImageOutput = {
        let _stillImageOutput = AVCaptureStillImageOutput()
        _stillImageOutput.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
        return _stillImageOutput
        }()

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.titleView = NavigationTitleLabel(title: NSLocalizedString("Avatar", comment: ""))

        navigationItem.rightBarButtonItem = nextButton

        view.backgroundColor = UIColor.whiteColor()

        pickAvatarState = .Default

        takePicturePromptLabel.textColor = UIColor.blackColor()
        takePicturePromptLabel.text = NSLocalizedString("Set an avatar", comment: "")

        openCameraButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        openCameraButton.backgroundColor = UIColor.yepTintColor()
        
        cameraRollButton.tintColor = UIColor.yepTintColor()
        captureButton.tintColor = UIColor.yepTintColor()
        retakeButton.setTitleColor(UIColor.yepTintColor(), forState: .Normal)
    }

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

        nextButton.enabled = false
    }

    // MARK: Helpers

    private func deviceWithMediaType(mediaType: String, preferringPosition position: AVCaptureDevicePosition) -> AVCaptureDevice? {
        let devices = AVCaptureDevice.devicesWithMediaType(mediaType)
        var captureDevice = devices.first as? AVCaptureDevice
        for device in devices as! [AVCaptureDevice] {
            if device.position == position {
                captureDevice = device
                break
            }
        }

        return captureDevice
    }

    // MARK: Actions

    func next(sender: UIBarButtonItem) {
        uploadAvatarAndGotoPickSkills()
    }

    @IBAction func tryOpenCamera(sender: UIButton) {

        AVCaptureDevice.requestAccessForMediaType(mediaType, completionHandler: { (granted) -> Void in
            if granted {
                self.openCamera()

            } else {
                dispatch_async(dispatch_get_main_queue()) {
                    YepAlert.confirmOrCancel(title: NSLocalizedString("Sorry", comment: ""), message: NSLocalizedString("Yep can not open your Camera!\nBut you can change it in iOS' Settings.\n", comment: ""), confirmTitle: NSLocalizedString("Change it now", comment: ""), cancelTitle: NSLocalizedString("Dismiss", comment: ""), inViewController: self, withConfirmAction: {

                        UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)

                    }, cancelAction: {
                    })
                }
            }
        })
    }

    private func openCamera() {

        dispatch_async(dispatch_get_main_queue()) {
            self.pickAvatarState = .CameraOpen
        }

        dispatch_async(sessionQueue) {

            if self.session.canAddInput(self.videoDeviceInput) {
                self.session.addInput(self.videoDeviceInput)

                dispatch_async(dispatch_get_main_queue()) {

                    self.cameraPreviewView.session = self.session
                    let orientation = AVCaptureVideoOrientation(rawValue: UIInterfaceOrientation.Portrait.rawValue)!
                    (self.cameraPreviewView.layer as! AVCaptureVideoPreviewLayer).connection.videoOrientation = orientation
                }
            }

            if self.session.canAddOutput(self.stillImageOutput){
                self.session.addOutput(self.stillImageOutput)
            }

            dispatch_async(dispatch_get_main_queue()) {
                self.session.startRunning()
            }
        }
    }

    @IBAction func tryOpenCameraRoll(sender: UIButton) {

        let status = PHPhotoLibrary.authorizationStatus()

        switch status {

        case .Authorized:
            openCameraRoll()

        case .NotDetermined:
            YepAlert.confirmOrCancel(title: NSLocalizedString("Notice", comment: ""), message: NSLocalizedString("Yep need to access your Camera Roll to pick avatar.", comment: ""), confirmTitle: NSLocalizedString("OK", comment: ""), cancelTitle: NSLocalizedString("Not now", comment: ""), inViewController: self, withConfirmAction: {

                PHPhotoLibrary.requestAuthorization { status in

                    switch status {

                    case .Authorized:
                        self.openCameraRoll()

                    default:
                        self.alertCanNotAccessCameraRoll()
                    }
                }

            }, cancelAction: {
            })

        default:
            alertCanNotAccessCameraRoll()
        }
    }

    func openCameraRoll() {
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.SavedPhotosAlbum) {
            let imagePicker = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum
            imagePicker.allowsEditing = false

            self.presentViewController(imagePicker, animated: true, completion: nil)
        }<commit_msg>not need prompt before do PHPhotoLibrary.requestAuthorization<commit_after>//
//  RegisterPickAvatarViewController.swift
//  Yep
//
//  Created by NIX on 15/3/18.
//  Copyright (c) 2015年 Catch Inc. All rights reserved.
//

import UIKit
import AVFoundation
import Photos

class RegisterPickAvatarViewController: UIViewController {
    
    @IBOutlet weak var avatarImageView: UIImageView!
    @IBOutlet weak var cameraPreviewView: CameraPreviewView!

    @IBOutlet weak var takePicturePromptLabel: UILabel!

    @IBOutlet weak var openCameraButton: BorderButton!

    @IBOutlet weak var cameraRollButton: UIButton!
    @IBOutlet weak var captureButton: UIButton!
    @IBOutlet weak var retakeButton: UIButton!

    lazy var nextButton: UIBarButtonItem = {
        let button = UIBarButtonItem(title: NSLocalizedString("Next", comment: ""), style: .Plain, target: self, action: "next:")
        return button
        }()

    var avatar = UIImage() {
        willSet {
            avatarImageView.image = newValue
        }
    }

    enum PickAvatarState {
        case Default
        case CameraOpen
        case Captured
    }

    var pickAvatarState: PickAvatarState = .Default {
        willSet {
            switch newValue {
            case .Default:
                openCameraButton.hidden = false

                cameraRollButton.hidden = true
                captureButton.hidden = true
                retakeButton.hidden = true

                cameraPreviewView.hidden = true
                avatarImageView.hidden = false

                avatarImageView.image = UIImage(named: "default_avatar")

                nextButton.enabled = false

            case .CameraOpen:
                openCameraButton.hidden = true

                cameraRollButton.hidden = false
                captureButton.hidden = false
                retakeButton.hidden = true

                cameraPreviewView.hidden = false
                avatarImageView.hidden = false

                captureButton.setImage(UIImage(named: "button_capture"), forState: .Normal)

                nextButton.enabled = false

            case .Captured:
                openCameraButton.hidden = true

                cameraRollButton.hidden = false
                captureButton.hidden = false
                retakeButton.hidden = false

                cameraPreviewView.hidden = true
                avatarImageView.hidden = false

                captureButton.setImage(UIImage(named: "button_capture_ok"), forState: .Normal)

                nextButton.enabled = true
            }
        }
    }

    lazy var sessionQueue = {
        return dispatch_queue_create("session queue", DISPATCH_QUEUE_SERIAL)
        }()

    lazy var session: AVCaptureSession = {
        let _session = AVCaptureSession()
        _session.sessionPreset = AVCaptureSessionPreset640x480

        return _session
        }()

    let mediaType = AVMediaTypeVideo

    lazy var videoDeviceInput: AVCaptureDeviceInput = {
        var error: NSError? = nil
        let videoDevice = self.deviceWithMediaType(self.mediaType, preferringPosition: .Front)
        return AVCaptureDeviceInput(device: videoDevice!, error: &error)
        }()

    lazy var stillImageOutput: AVCaptureStillImageOutput = {
        let _stillImageOutput = AVCaptureStillImageOutput()
        _stillImageOutput.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
        return _stillImageOutput
        }()

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.titleView = NavigationTitleLabel(title: NSLocalizedString("Avatar", comment: ""))

        navigationItem.rightBarButtonItem = nextButton

        view.backgroundColor = UIColor.whiteColor()

        pickAvatarState = .Default

        takePicturePromptLabel.textColor = UIColor.blackColor()
        takePicturePromptLabel.text = NSLocalizedString("Set an avatar", comment: "")

        openCameraButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        openCameraButton.backgroundColor = UIColor.yepTintColor()
        
        cameraRollButton.tintColor = UIColor.yepTintColor()
        captureButton.tintColor = UIColor.yepTintColor()
        retakeButton.setTitleColor(UIColor.yepTintColor(), forState: .Normal)
    }

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

        nextButton.enabled = false
    }

    // MARK: Helpers

    private func deviceWithMediaType(mediaType: String, preferringPosition position: AVCaptureDevicePosition) -> AVCaptureDevice? {
        let devices = AVCaptureDevice.devicesWithMediaType(mediaType)
        var captureDevice = devices.first as? AVCaptureDevice
        for device in devices as! [AVCaptureDevice] {
            if device.position == position {
                captureDevice = device
                break
            }
        }

        return captureDevice
    }

    // MARK: Actions

    func next(sender: UIBarButtonItem) {
        uploadAvatarAndGotoPickSkills()
    }

    @IBAction func tryOpenCamera(sender: UIButton) {

        AVCaptureDevice.requestAccessForMediaType(mediaType, completionHandler: { (granted) -> Void in
            if granted {
                self.openCamera()

            } else {
                dispatch_async(dispatch_get_main_queue()) {
                    YepAlert.confirmOrCancel(title: NSLocalizedString("Sorry", comment: ""), message: NSLocalizedString("Yep can not open your Camera!\nBut you can change it in iOS' Settings.\n", comment: ""), confirmTitle: NSLocalizedString("Change it now", comment: ""), cancelTitle: NSLocalizedString("Dismiss", comment: ""), inViewController: self, withConfirmAction: {

                        UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)

                    }, cancelAction: {
                    })
                }
            }
        })
    }

    private func openCamera() {

        dispatch_async(dispatch_get_main_queue()) {
            self.pickAvatarState = .CameraOpen
        }

        dispatch_async(sessionQueue) {

            if self.session.canAddInput(self.videoDeviceInput) {
                self.session.addInput(self.videoDeviceInput)

                dispatch_async(dispatch_get_main_queue()) {

                    self.cameraPreviewView.session = self.session
                    let orientation = AVCaptureVideoOrientation(rawValue: UIInterfaceOrientation.Portrait.rawValue)!
                    (self.cameraPreviewView.layer as! AVCaptureVideoPreviewLayer).connection.videoOrientation = orientation
                }
            }

            if self.session.canAddOutput(self.stillImageOutput){
                self.session.addOutput(self.stillImageOutput)
            }

            dispatch_async(dispatch_get_main_queue()) {
                self.session.startRunning()
            }
        }
    }

    @IBAction func tryOpenCameraRoll(sender: UIButton) {

        let status = PHPhotoLibrary.authorizationStatus()

        switch status {

        case .Authorized:
            openCameraRoll()

        case .NotDetermined:

            PHPhotoLibrary.requestAuthorization { status in

                switch status {

                case .Authorized:
                    self.openCameraRoll()

                default:
                    self.alertCanNotAccessCameraRoll()
                }
            }

        default:
            alertCanNotAccessCameraRoll()
        }
    }

    func openCameraRoll() {
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.SavedPhotosAlbum) {
            let imagePicker = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum
            imagePicker.allowsEditing = false

            self.presentViewController(imagePicker, animated: true, completion: nil)
        }
{'fraction_non_alphanumeric': 0.07640339024689842, 'fraction_numerical': 0.0018425254882692545, 'mean_word_length': 2.187744714173845, 'pattern_counts': {'":': 0, '<': 3, '<?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': '418394', 'n_tokens_mistral': 4310, 'n_tokens_neox': 4033, 'n_words': 835}