//
// Created by Alexander Zalutskiy on 07.08.15.
// Copyright (c) 2015 Alexandr Zalutskiy. All rights reserved.
//

import UIKit
import MessageUI

class CabinetViewController: ViewControllerWithMenu, MFMailComposeViewControllerDelegate {
    
    @IBOutlet weak var todayBalanceTitleLabel: UILabel!
    @IBOutlet weak var phoneTitleLabel: UILabel!
    @IBOutlet weak var accountBalanceTitleLabel: UILabel!
    @IBOutlet weak var notificationsHeight: NSLayoutConstraint!
    @IBOutlet weak var historyHeight: NSLayoutConstraint!
    @IBOutlet weak var settingsHeight: NSLayoutConstraint!
    @IBOutlet weak var cashAndPaymentsHeight: NSLayoutConstraint!
    @IBOutlet weak var offersHeight: NSLayoutConstraint!
    @IBOutlet weak var myServicesHeight: NSLayoutConstraint!
    @IBOutlet var BoxesHeight: [NSLayoutConstraint]!
    @IBOutlet var buttons: [ButtonView]!
    @IBOutlet weak var dividerView: UIView!
    @IBOutlet var cashAndPaymentsView: ButtonView!
    @IBOutlet var payButton: GreenButton!
    @IBOutlet var clientInfoView: UIView!
    @IBOutlet var scrollView: UIScrollView!
    @IBOutlet var contentView: UIView!
    @IBOutlet var _labels: [UILabel]!
    @IBOutlet private weak var _fioLabel: UILabel!
    @IBOutlet private weak var _accountLabel: UILabel!
    @IBOutlet private weak var _phoneNumberLabel: UILabel!
    @IBOutlet private weak var _balanceLabel: UILabel!
    @IBOutlet private weak var _activityIndicatorView: UIActivityIndicatorView!
    @IBOutlet weak var offersButton: VerticalButton!
    @IBOutlet weak var myServicesButton: VerticalButton!
    @IBOutlet weak var cashAndPaymentsButton: VerticalButton!
    @IBOutlet weak var historyButton: VerticalButton!
    @IBOutlet weak var settingsButton: VerticalButton!
    @IBOutlet weak var notificationsButton: VerticalButton!
    @IBOutlet var myServicesView: ButtonView!
    @IBOutlet var offersView: ButtonView!
    @IBOutlet var settingsView: ButtonView!
    @IBOutlet var historyView: ButtonView!
    @IBOutlet var notificationsView: ButtonView!
    @IBOutlet weak var webView: UIWebView!
    @IBOutlet weak var textView: UITextView!
    @IBOutlet weak var groupBox: UIView!
    @IBOutlet weak var groupBoxHeight: NSLayoutConstraint!
    
    let defaults = NSUserDefaults.standardUserDefaults()
    
    private var titleLabel : UILabel?
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        registerNotificationObservers()
        
        if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
            requestDynamicMenu()
        }
        
        self.automaticallyAdjustsScrollViewInsets = false
        
        registerButtonHandlers()
        
        configureScrollView()
        
        self.navigationItem.title = §"menu.cabinet"
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CabinetViewController.updateLabels),
                                                         name: AbonentInfoManager.NotificationNames.Update, object: AbonentInfoManager.sharedInstance)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CabinetViewController.showError(_:)),
                                                         name: AbonentInfoManager.NotificationNames.Error, object: AbonentInfoManager.sharedInstance)
        
        AbonentInfoManager.sharedInstance.updateUserInfo()
        
        if AbonentInfoManager.sharedInstance.abonentInfo != nil {
            updateLabels()
        } else {
            hideLabels()
        }
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        configureBlueNavbar()
        configureViews()
        localizeSubviews()
    }
    
    func sendEmailButtonTapped(vc: UIViewController? = nil) {
        let mailComposeViewController = configuredMailComposeViewController()
        
        if MFMailComposeViewController.canSendMail() {
            if let vc = vc {
                vc.presentViewController(mailComposeViewController, animated: true, completion: nil)
            } else {
                self.presentViewController(mailComposeViewController, animated: true, completion: {
                })
            }
        } else {
            self.showSendMailErrorAlert()
        }
    }
    
    func showSendMailErrorAlert() {
        let sendMailErrorAlert = UIAlertView(title: "Could Not Send Email", message: "Your device could not send e-mail.  Please check e-mail configuration and try again.", delegate: self, cancelButtonTitle: "OK")
        sendMailErrorAlert.show()
    }
    
    func configuredMailComposeViewController() -> MFMailComposeViewController {
        
        let mailComposerVC = MFMailComposeViewController()
        mailComposerVC.mailComposeDelegate = self
        
        let logFileData = NSData(contentsOfURL: AppDelegate.getMyLogPath())
        
        let now = NSDate()
        let formatter = NSDateFormatter()
        formatter.dateFormat = "yyyy/MM/dd' 'HH:mm:ss'"
        formatter.timeZone = NSTimeZone.localTimeZone()
        
        let message: String = ""
        
        mailComposerVC.setToRecipients(["assylkhan.rakhatov@gmail.com", "assylkhan.rakhatov@mail.ru"])
        mailComposerVC.setSubject(": " + formatter.stringFromDate(now))
        mailComposerVC.setMessageBody(message, isHTML: false)
        mailComposerVC.addAttachmentData(logFileData!, mimeType: "log", fileName: "console.log")
        
        return mailComposerVC
    }
    
    @IBAction func payClicked(sender: UIButton) {
        performSegueWithIdentifier("showPayment", sender: nil)
    }
    
    private func configureViews() {
        dividerView.backgroundColor = Color.DividerDarkBlueColor
        clientInfoView.backgroundColor = Color.KTDefaultBlueColor
    }
    
    func localizeSubviews() {
        todayBalanceTitleLabel.setTextAndSizeToFit(LS("cabinet.label.today_balance"))
        phoneTitleLabel.setTextAndSizeToFit(LS("cabinet.label.phone"))
        accountBalanceTitleLabel.setTextAndSizeToFit(LS("cabinet.label.guid_cash"))
        payButton.setTitle(LocalizedString("cabinet.button.pay"), forState: .Normal)
    }
    
    func resizeScrollViewToFit() {
        contentView.resizeToFitSubviews()
        scrollView.contentSize = CGSize(width: scrollView.frame.size.width, height: contentView.frame.height)
    }
    
    func registerButtonHandlers() {
        myServicesButton.addTarget(self, action: #selector(CabinetViewController.myService_TouchUpInside(_:)), forControlEvents: .TouchUpInside)
        offersButton.addTarget(self, action: #selector(CabinetViewController.offers_TouchUpInside(_:)), forControlEvents: .TouchUpInside)
        cashAndPaymentsButton.addTarget(self, action: #selector(CabinetViewController.cash_TouchUpInside(_:)), forControlEvents: .TouchUpInside)
        settingsButton.addTarget(self, action: #selector(CabinetViewController.settings_TouchUpInside(_:)), forControlEvents: .TouchUpInside)
        historyButton.addTarget(self, action: #selector(CabinetViewController.softwareRent_TouchUpInside(_:)), forControlEvents: .TouchUpInside)
        notificationsButton.addTarget(self, action: #selector(CabinetViewController.notifications_TouchUpInside(_:)), forControlEvents: .TouchUpInside)
    }
    
    func addGestureRecognizer(targetView: UIView, selector: Selector) {
        let myTapRecognizer = UITapGestureRecognizer(target: self, action: selector)
        myTapRecognizer.cancelsTouchesInView = false
        myTapRecognizer.delaysTouchesBegan = false
        myTapRecognizer.delaysTouchesEnded = false
        targetView.userInteractionEnabled = true
        targetView.addGestureRecognizer(myTapRecognizer)
    }
    
    func panGesture(gesture: UIPanGestureRecognizer) {
        if gesture.state == UIGestureRecognizerState.Ended {
            print("stateEnded: \(gesture.state == UIGestureRecognizerState.Ended)")
        } else if gesture.state == UIGestureRecognizerState.Cancelled {
            print("stateCancelled: \(gesture.state == UIGestureRecognizerState.Cancelled)")
        } else if gesture.state == UIGestureRecognizerState.Failed {
            print("stateFailed: \(gesture.state == UIGestureRecognizerState.Failed)")
        }
    }
    
    func notifications_TouchUpInside(sender: UIGestureRecognizer?) {
        print("notifications_TouchUpInside")
        performSegueWithIdentifier("show_claim", sender: nil)
    }
    
    func softwareRent_TouchUpInside(sender: UIGestureRecognizer?) {
        print("history_TouchUpInside")
        performSegueWithIdentifier("software_rent", sender: nil)
    }
    
    func settings_TouchUpInside(sender: UIGestureRecognizer?) {
        print("settings_TouchUpInside")
        settingButton_TouchUpInside(sender)
    }
    
    func offers_TouchUpInside(sender: UIGestureRecognizer?) {
        performSegueWithIdentifier("goToOffers", sender: nil)
        print("offers_TouchUpInside")
    }
    
    func myService_TouchUpInside(sender: UIGestureRecognizer?) {
        performSegueWithIdentifier("goToMyServices", sender: nil)
    }
    
    func cash_TouchUpInside(sender: UIGestureRecognizer?) {
        self.performSegueWithIdentifier("cashesAndPayments", sender: nil)
        print("cash_TouchUpInside")
    }
    
    private func configureScrollView() {
        groupBox.sizeToFit()
        groupBoxHeight.constant = groupBox.frame.height
        scrollView.scrollIndicatorInsets = UIEdgeInsets(top: 0, left: 0, bottom: scrollView.scrollIndicatorInsets.bottom, right: 0)
    }
    
    private func getIndicator() -> UIActivityIndicatorView {
        let loadingIndicator: UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(50, 10, 37, 37)) as UIActivityIndicatorView
        loadingIndicator.center = self.view.center
        loadingIndicator.hidesWhenStopped = true
        loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
        loadingIndicator.startAnimating()
        return loadingIndicator
    }
    
    func requestDynamicMenu() {
        
        if !DynamicMenuManager.sharedInstance().loaded {
            
            SpinneredAlert.show(self)
            
            DynamicMenuManager.sharedInstance().getMenu({ error in
                
                if let error = error {
                    
                    AlertViewUtil.showErrorAlert(LS("error"), message: error)
                    
                } else {
                    
                    DynamicMenuManager.sharedInstance().loaded = true
                    
                    self.dismissViewControllerAnimated(true, completion: {
                        NSNotificationCenter.defaultCenter().postNotificationName("ReloadTable", object: nil)
                    })
                }
            })
        }
    }
    
    func loginModalClosed() {
        if Facade.accessToken != nil && Facade.clientId != nil {
            requestDynamicMenu()
        }
    }
    
    func registerNotificationObservers() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CabinetViewController.loginModalClosed), name: Notification.loginModalClosed, object: nil)
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    @IBAction func cpanelButton_TouchUpInside(sender: AnyObject?) {
        
    }
    
    @IBAction func settingButton_TouchUpInside(sender: AnyObject?) {
        performSegueWithIdentifier("goToSettings", sender: nil)
    }
    
    // MARK: Helpers
    
    private func hideLabels() {
        
        _activityIndicatorView.startAnimating()
        
        for label in _labels {
            label.hidden = true
        }
    }
    
    func updateLabels() {
        
        if let abonentInfo = AbonentInfoManager.sharedInstance.abonentInfo {
            
            _activityIndicatorView.stopAnimating()
            
            for label in _labels {
                label.hidden = false
            }
            
            _fioLabel.text = abonentInfo.name

            defaults.setValue(abonentInfo.name, forKey: "AbonentName")

            _accountLabel.text = "\(Facade.serverId!)-\(Facade.accountId!)"
            
            if let isEmpty = abonentInfo.phones?.isEmpty where !isEmpty {
                _phoneNumberLabel.text = "\(abonentInfo.phones![0])"
            } else {
                _phoneNumberLabel.text = "-"
            }
            
            if (abonentInfo.phones?.count > 0) {
                SharedDataManager.sharedInstance().abonentPhoneNumber = "\(abonentInfo.phones![0])"
            }
            
            let currency = "\(abonentInfo.balance ?? 0)".stringByReplacingOccurrencesOfString(".", withString: ",")
            _balanceLabel.text = "\(currency) тг"
        }
        
    }
    
    func makeNameString(str: String) -> String {
        let nameArr = str.characters.split{$0 == " "}.map(String.init)
        return "\(nameArr[0]) \(nameArr[1])\n\(nameArr[2])"
    }
    
    func showError(notification: NSNotification) {
        _activityIndicatorView.stopAnimating()
        let error = notification.userInfo![FacadeNotificationErrorKey] as! NSError
        let alert = UIAlertView(title: §"error", message: error.localizedDescription, delegate: nil, cancelButtonTitle: §"cancel")
        alert.show()
    }
    
}

// MFMailComposeViewControllerDelegate
extension CabinetViewController {
    
    func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
        
        debugPrint("mailComposeController didFinishWithResult begin")
        
        switch (result) {
        case MFMailComposeResult.Cancelled:
            break
            
        case MFMailComposeResult.Saved:
            break
            
        case MFMailComposeResult.Sent:
            print("MFMailComposeResultSent")
            let documentsUrl =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! as NSURL
            let destinationUrl = documentsUrl.URLByAppendingPathComponent("console.log")
            do {
                try NSFileManager.defaultManager().removeItemAtURL(destinationUrl!)
            } catch {
                print(error)
            }
            break
            
        case MFMailComposeResult.Failed:
            print("MFMailComposeResultFailed")
            break
            
        default:
            break
        }
        
        //Dismiss the mailViewController.
        
        self.dismissViewControllerAnimated(true, completion: nil)
        debugPrint("mailComposeController didFinishWithResult end")
    }
}

extension CabinetViewController {
    override var localizedId: String {
        return "cabinet"
    }
}
