//
//  Mail.swift
//  iPOS
//
//  Created by BBC on 10/04/17.
//  Copyright © 2017 BBC. All rights reserved.
//

import Foundation
import MessageUI

class Mail {
    var mailComposeVC = MFMailComposeViewController()
    var viewController: UIViewController? = nil
    var email: String? = nil
    var subject: String? = nil
    var message: String = ""
    var isHTMLMessage: Bool? = nil
    
    var mailAttachments: [MailAttachment] = []
    
    func composeMailImage() {
        mailComposeVC.delegate = viewController as! UINavigationControllerDelegate?
        mailComposeVC.mailComposeDelegate = viewController as! MFMailComposeViewControllerDelegate?
        
        self.addMail()
        self.addSubject()
        self.addAttachments()
        
        mailComposeVC.setMessageBody(message, isHTML: isHTMLMessage!)
        viewController?.present(mailComposeVC, animated: true, completion: nil)
    }
    
    private func addMail(){
        if let email = self.email{
            mailComposeVC.setToRecipients([email])
        }
    }
    
    private func addSubject(){
        if let subject = self.subject{
            mailComposeVC.setSubject(subject)
        }
    }
    
    private func addAttachments(){
        for mailAttachment in self.mailAttachments{
            mailComposeVC.addAttachmentData(mailAttachment.attachment as Data, mimeType: mailAttachment.attachmentType, fileName: mailAttachment.attachmentName)
        }
    }
    
    static func showSendMailErrorAlert(_ viewController: UIViewController) {
        let sendMailErrorAlert = UIAlertController(title: Util.getString("Could Not Send Email"), message: Util.getString("Your device could not send e-mail.  Please check e-mail configuration and try again."), preferredStyle: .alert)
        
        let OKAction = UIAlertAction(title: "OK", style: .default, handler : { (action) -> Void in
            return
        })
        sendMailErrorAlert.addAction(OKAction)
        viewController.present(sendMailErrorAlert, animated: true, completion: nil)
    }
    
    class MailAttachment {
        var attachment: NSData = NSData()
        var attachmentType: String = "application/pdf"
        var attachmentName: String = ""
    }
}
