//
//  DocumentDetailViewController.swift
//  iPOS
//
//  Created by Apple iMac on 12/07/2017.
//  Copyright © 2017 BBC. All rights reserved.
//

import Foundation
import UIKit
import MessageUI

class DocumentDetailViewController: UIViewController, UIWebViewDelegate, UINavigationControllerDelegate {
    
    @IBOutlet weak var webView: UIWebView!
    @IBOutlet weak var sendMailButton: UIButton!
    @IBOutlet weak var printButton: UIButton!
    
    var contact: Contact!
    var documentId: String?
    var documentTypeId: Int?
    var binaryData: String?
    var layoutId: Int?
    var layoutType: String?
    var viewTitle: String?
    var MINEType: String = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.webView.delegate = self
        self.createMineType()
        self.loadDocument()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationItem.title = viewTitle
    }
    
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    func createMineType(){
        if let documentName = viewTitle{
            if documentName.hasSuffix(".pdf"){
                MINEType = "application/pdf"
            }
            else if documentName.hasSuffix(".png"){
                MINEType = "image/png"
            }
            else if documentName.hasSuffix(".jpg") || documentName.hasSuffix(".jpeg"){
                MINEType = "image/jpeg"
            }
            else if documentName.hasSuffix(".tif") || documentName.hasSuffix(".tiff"){
                MINEType = "image/tiff"
            }
            else if documentName.hasSuffix(".rtf"){
                MINEType = "application/rtf"
            }
            else if documentName.hasSuffix(".xls"){
                MINEType = "application/vnd.ms-excel"
            }
        }
    }
    
    func loadDocument(){
        self.setButtonStatus(isEnabled: false)
        
        if self.layoutId == nil && self.binaryData != nil{
            self.showDocument()
        }
        else if self.layoutId != nil{
            State.loadDataReport(attachmentId: documentId!) { SensitiveDataReportResult in
                    self.binaryData = SensitiveDataReportResult.document
                    self.showDocument()
            }
        }
        else if self.documentId != nil && self.MINEType.contains("image") == false{
            State.loadDataReport(attachmentId: documentId!) { SensitiveDataReportResult in
                    self.binaryData = SensitiveDataReportResult.document
                    self.showDocument()
            }
        }
        else if let documentId = self.documentId {  // Safe unwrapping
                State.loadImgDocument(contactId: contact.ContactId, documentId: documentId) { result in
                    if let result = result, !result.isEmpty {
                        self.binaryData = result[0].binaryData
                        self.showDocument()
                    }
                else{
                    Util.GeneralAlert(viewController: self, message: Util.getString("An error has occured.\nPlease try again!"))
                }
            }
        }
    }
    
    func showDocument(){
        if MINEType != ""{
            if let binary = binaryData{
                let decodedData = Data(base64Encoded: binary)
                if let _decodedData = decodedData{
                    webView.load(_decodedData, mimeType: MINEType, textEncodingName:  "UTF-8", baseURL: NSURL(string: "")! as URL)
                    self.setButtonStatus(isEnabled: true)
                }
            }
        }
        else{
            Util.GeneralAlert(viewController: self, message: Util.getString("The document type is not supported"))
            self.setButtonStatus(isEnabled: false)
        }
    }
    
    func setButtonStatus(isEnabled: Bool){
        self.sendMailButton.isEnabled = isEnabled
        self.printButton.isEnabled = isEnabled
    }
    
    @IBAction func sendMailButton_Click(_ sender: Any) {
        if let email = contact.Email, !email.isEmpty{
            self.sendMail()
        }
        else{
            Util.GeneralAlert(viewController: self, message: Util.getString("This contact doesn't have an email address."))
        }
    }
    
    func sendMail(){
        var attachments: [EmailAttachment]? = nil
            
        if self.binaryData != nil{
            attachments = [EmailAttachment]()
            let attachment: EmailAttachment = EmailAttachment()
            attachment.document = self.binaryData!
            attachment.name = self.viewTitle!
            
            attachments!.append(attachment)
        }
        
        var reportType = "EMAIL_DOC"
        if let documentType = self.documentTypeId{
            if documentType == 0 { //INVOICE
                reportType = "EMAIL_INV"
            }
            else if documentType == 1{ //Privacy
                reportType = "EMAIL_PRV"
            }
        }
        
        let email: EmailRequest = EmailRequest(email: self.contact.Email!, reportType: reportType, attachments: attachments)
        
        State.sendEmail(emailRequest: email) { (result) in
            if result{
                Util.GeneralAlertAutoDismiss(viewController: self, message: Util.getString("The email was sent successfully!"), time: 1.5)
            }
            else{
                Util.AlertRetryAction(viewController: self, title: Util.getString("Error"), message: Util.getString("The email could not be sent!"), actionOnRetry: {
                    self.sendMail()
                    
                }, actionOnCancel: {})
            }
        }
    }
    
    @IBAction func printButton_Click(_ sender: Any) {
        if let decodedData = self.binaryData{
            if let pdf = NSData(base64Encoded: decodedData, options: NSData.Base64DecodingOptions(rawValue: 0)){
                printPDFRaport(pdfData: pdf) { result in
                    return
                }
            }
        }
    }
    
    func printPDFRaport(pdfData: NSData,completionHandler: @escaping (Bool?) -> Void){
        let printController = UIPrintInteractionController.shared
        
        let printInfo = UIPrintInfo(dictionary:nil)
        printInfo.outputType = UIPrintInfo.OutputType.general
        
        if let title = viewTitle{
           printInfo.jobName = title
        }
        
        printController.printInfo = printInfo
        printController.printingItem = pdfData
        printController.present(animated: true) { (result, status, error) in
            completionHandler(status)
        }
    }
}
