import UIKit
import WowonderMessengerSDK
import GoogleMobileAds
import MessageUI
import FBAudienceNetwork

class InviteFriendsVC: BaseVC {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var tableView: UITableView!
    
    // MARK: - Properties
    
    var delegate: SelectContactDetailDelegate?
    
    // MARK: - View Life Cycles
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.initialConfig()
    }
    
    // MARK: - Selectors
    
    // Back Button Action
    @IBAction func backButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.navigationController?.popViewController(animated: true)
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.tableViewSetup()
        self.fetchContacts {
            self.tableView.reloadData()
        }
    }
    
    // TableView Setup
    func tableViewSetup() {
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.register( UINib(resource: R.nib.inviteFriendsTableCell), forCellReuseIdentifier: R.reuseIdentifier.inviteFriendsTableCell.identifier)
    }
    
    func sendMessageToNumber(number: String, message: String) {
        guard MFMessageComposeViewController.canSendText() else {
            print("Unable to send messages.")
            return
        }
        let controller = MFMessageComposeViewController()
        controller.body = message
        controller.recipients = [number]
        controller.messageComposeDelegate = self
        present(controller, animated: true, completion: nil)
    }
    
}

// MARK: - Extensions

// MARK: TableView Setup
extension InviteFriendsVC: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.contacts.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.inviteFriendsTableCell.identifier) as! InviteFriendsTableCell
        cell.nameLabel.text = self.contacts[indexPath.row].name
        cell.phoneNumberLabel.text = self.contacts[indexPath.row].phoneNumber
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        AppInstance.instance.addCount = AppInstance.instance.addCount! + 1
        self.sendMessageToNumber(number: self.contacts[indexPath.row].phoneNumber, message: ControlSettings.inviteFriendText)
    }
    
}

// MARK: MFMessageComposeViewControllerDelegate Methods
extension InviteFriendsVC: MFMessageComposeViewControllerDelegate {
    
    func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) {
        self.dismiss(animated: true, completion: nil)
    }
    
}
