public class InterFaxController {

    //public String att { get; set; }
    public String recordId {get; set;}
    public String pdfPreview {get; set;}
    public String faxNumber {get;set;}
    public String messageId {get;set;}
    public String selectedValue {get;set;}
    Public Boolean faxViewer {get;set;}
    public List<Attachment> attachments {get;set;}
    public List<Attachment> fileattachments {get;set;}
    Public List<ContentDocument> files {get;set;}
    //private List<String> base64List = new List<String>();
    private Map<Id, Attachment> attachmentMap = new Map<Id, Attachment>();
    //private Map<Id, ContentDocumentLink> contentDocumentLinkMap = new Map<Id, ContentDocumentLink>();
    public String attachmentId {get;set;}
    public List<InterFaxJSON.OutboundFaxDetail> listOutboundFaxes {get;set;}
    public List<InterFaxJSON.InboundFaxDetail > listInboundFaxes {get;set;}
     // Specify the required user name and password to access the endpoint
     // As well as the header and header information
 
     String username = 'yourinterfaxid';
     String password = 'redacted';
     
    public InterFaxController() {
        this.recordId = ApexPages.currentPage().getParameters().get('id');
        this.attachments = new List<Attachment> ();
        this.fileattachments = new List<Attachment> ();
        this.listOutboundFaxes = new List<InterFaxJSON.OutboundFaxDetail>();
        this.listInboundFaxes = new List<InterFaxJSON.InboundFaxDetail>();
    }    
    
    public List<Attachment> getAttachments(){
        return this.attachments;
    }
    public List<Attachment> getFileAttachments(){
        return this.fileattachments;
    }
    
    public List<ContentDocument> getFiles(){
        return this.files;
    }
    
    public void listAttachments() { 
        this.attachments = [select Id, Name, BodyLength, Body,  Description, contenttype from attachment where ParentId = :this.recordId];
        for(Attachment at: this.attachments){
            this.attachmentMap.put(at.id, at);    
        }
        this.attachments = [select Id, Name, BodyLength, Body,  Description, contenttype from attachment where ParentId = :this.recordId];
        List<ContentDocumentLink> documentLinks = [SELECT  ContentDocument.Id, ContentDocument.LatestPublishedVersion.VersionData FROM ContentDocumentLink WHERE LinkedEntityId = :this.recordId];
        List < String > idList = new List < String >();  
        for(ContentDocumentLink l: documentLinks){
            idList.add(l.ContentDocumentId);
            //contentDocumentLinkMap.put(l.ContentDocumentId, l);
            //base64List.add(EncodingUtil.base64Encode(l.ContentDocument.LatestPublishedVersion.VersionData).substring(0,10));
        }
        this.files = [SELECT FileType, Id, Title FROM ContentDocument WHERE Id IN :idList];  
    }
    
    public void listFileAttachments() {

     
    }
    
    public String getPDF() {
          return pdfPreview;
          
    }
    
    public void sendFaxAttachment() { 
        System.debug('In sendFax:'+this.attachmentId);
        System.debug('Fax:'+faxNumber);
        
        HttpRequest req = new HttpRequest();
     req.setEndpoint('https://rest.interfax.net/outbound/faxes?faxNumber='+faxNumber);
     req.setMethod('POST');
        req.setBodyAsBlob(this.attachmentMap.get(this.attachmentId).body);
     
  
     Blob headerValue = Blob.valueOf(username + ':' + password);
     String authorizationHeader = 'Basic ' +
     EncodingUtil.base64Encode(headerValue);
     req.setHeader('Authorization', authorizationHeader);
        req.setHeader('Content-Type', 'application/pdf');
   
     // Create a new http object to send the request object
     // A response object is generated as a result of the request  
  
     Http http = new Http();
     HTTPResponse res = http.send(req);
     System.debug(res.getBody());
     Integer resStatus = res.getStatusCode();
        if(resStatus == 201) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM, 'Fax sent succesfully.' + res.getBody()));
        } else {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Error occurred while sending the fax.  HTTP Status Code: ' + resStatus));
        }
    }
    
    
    public void sendFax() { 
        System.debug('In sendFax:'+this.attachmentId);
        System.debug('Fax:'+faxNumber);
        ContentDocumentLink cdl = [SELECT ContentDocument.Id, ContentDocument.LatestPublishedVersion.VersionData FROM ContentDocumentLink WHERE LinkedEntityId = :this.recordId AND ContentDocumentId = :this.attachmentId];
        HttpRequest req = new HttpRequest();
     req.setEndpoint('https://rest.interfax.net/outbound/faxes?faxNumber='+faxNumber);
     req.setMethod('POST');
        //req.setBodyAsBlob(this.attachmentMap.get(this.attachmentId).body);
        req.setBodyAsBlob(cdl.ContentDocument.LatestPublishedVersion.VersionData);
     
  
     Blob headerValue = Blob.valueOf(username + ':' + password);
     String authorizationHeader = 'Basic ' +
     EncodingUtil.base64Encode(headerValue);
     req.setHeader('Authorization', authorizationHeader);
        req.setHeader('Content-Type', 'application/pdf');
   
     // Create a new http object to send the request object
     // A response object is generated as a result of the request  
  
     Http http = new Http();
     HTTPResponse res = http.send(req);
     System.debug(res.getBody());
     Integer resStatus = res.getStatusCode();
        if(resStatus == 201) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM, 'Fax sent succesfully.' + res.getBody()));
        } else {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Error occurred while sending the fax.  HTTP Status Code: ' + resStatus));
        }
    }
    
     public void fetchInboundFaxes() { 
        System.debug('In fetchInboundFaxes:');
        HttpRequest req = new HttpRequest();
     req.setEndpoint('https://rest.interfax.net/inbound/faxes');
     req.setMethod('GET');

  Blob headerValue = Blob.valueOf(username + ':' + password);
     String authorizationHeader = 'Basic ' +
     EncodingUtil.base64Encode(headerValue);
     req.setHeader('Authorization', authorizationHeader);
        
     // Create a new http object to send the request object
     // A response object is generated as a result of the request  
  
     Http http = new Http();
     HTTPResponse res = http.send(req);
     System.debug(res.getBody());
     Integer resStatus = res.getStatusCode();
        if(resStatus == 200) {
            //ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM, 'Fax sent succesfully.'));
            this.listInboundFaxes = InterFaxJSON.parseInboundFaxDetail(res.getBody());
            system.debug('size: '+listOutboundFaxes.size());
        } else {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Error occurred while checking for inbound faxes. HTTP Status Code: ' + resStatus));
        }
    }
    
    
    public void getInboundImage() { 
    System.debug('in getInboundImage:');
    HttpRequest req = new HttpRequest();
     req.setEndpoint('https://rest.interfax.net/inbound/faxes/'+ messageId + '/image');
     req.setMethod('GET');

     Blob headerValue = Blob.valueOf(username + ':' + password);
     String authorizationHeader = 'Basic ' +
     EncodingUtil.base64Encode(headerValue);
     req.setHeader('Authorization', authorizationHeader);
        
     // Create a new http object to send the request object
     // A response object is generated as a result of the request  
  
     Http http = new Http();
     HTTPResponse res = http.send(req);
     System.debug(res.getBody());
     Blob faxImage = res.getBodyAsBlob();
     Integer resStatus = res.getStatusCode();
        if(resStatus == 200) {
            //ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM, 'Fax sent succesfully.'));
            //this.listInboundFaxes = InterFaxJSON.parseInboundFaxDetail(res.getBody());
            //system.debug('size: '+listOutboundFaxes.size());'
            system.debug('TransactionID: ' + messageId);
            Attachment attach = new Attachment();
            attach.contentType = 'application/pdf';
            attach.name = messageId + '.pdf';
            attach.parentId = this.recordId;
            attach.body = faxImage;
            try{
                insert attach;
            }
            catch(System.DMLException e) {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Error occurred while saving Fax.'));
            }
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Info, 'Attachment saved successfully.'));
        } else {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Error occurred while downloading Fax. HTTP Status Code: ' + resStatus +' MessageID: '+ this.messageId));
        }
    }
    
    public void getInboundContent() { 
    System.debug('in getInboundContent:');
    HttpRequest req = new HttpRequest();
     req.setEndpoint('https://rest.interfax.net/inbound/faxes/'+ messageId + '/image');
     req.setMethod('GET');

     Blob headerValue = Blob.valueOf(username + ':' + password);
     String authorizationHeader = 'Basic ' +
     EncodingUtil.base64Encode(headerValue);
     req.setHeader('Authorization', authorizationHeader);
        
     // Create a new http object to send the request object
     // A response object is generated as a result of the request  
  
     Http http = new Http();
     HTTPResponse res = http.send(req);
     System.debug(res.getBody());
     Blob faxImage = res.getBodyAsBlob();
     Integer resStatus = res.getStatusCode();
        if(resStatus == 200) {

            // ------ Step #1 - Upload the File ------
            system.debug('TransactionID: ' + messageId);
            ContentVersion conVer = new ContentVersion();
            conVer.ContentLocation = 'S'; // S specify this document is in SF, use E for external files
            conVer.PathOnClient = messageID + '.pdf' ; // The files name, extension is very important here which will help the file in preview.
            conVer.Title = messageID + '.pdf'; // Display name of the files
            conVer.VersionData = faxImage; // converting your binary string to Blog
            
            try{
                insert conVer;
            }
            catch(System.DMLException e) {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Error occurred while saving Fax.'));
            }
            
            // ------ Step #2 - Link to Object (Optional) ------
            ///*
            // First get the content document Id from ContentVersion
            Id conDoc = [SELECT ContentDocumentId FROM ContentVersion WHERE Id =:conVer.Id].ContentDocumentId;
             
            //Create ContentDocumentLink
            ContentDocumentLink cDe = new ContentDocumentLink();
            cDe.ContentDocumentId = conDoc;
            cDe.LinkedEntityId = this.recordId; // you can use objectId,GroupId etc
            cDe.ShareType = 'I'; // Inferred permission, checkout description of ContentDocumentLink object for more details
            cDe.Visibility = 'AllUsers';
            insert cDe;
            //*/
            
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Info, 'File saved successfully.'));
        } else {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Error occurred while downloading Fax. HTTP Status Code: ' + resStatus +' MessageID: '+ this.messageId));
        }
    }
 
    public void getRenderPDF() { 
    System.debug('in getInboundImage:');
    HttpRequest req = new HttpRequest();
     req.setEndpoint('https://rest.interfax.net/inbound/faxes/'+ messageId + '/image');
     req.setMethod('GET');

     Blob headerValue = Blob.valueOf(username + ':' + password);
     String authorizationHeader = 'Basic ' +
     EncodingUtil.base64Encode(headerValue);
     req.setHeader('Authorization', authorizationHeader);
        
     // Create a new http object to send the request object
     // A response object is generated as a result of the request  
  
     Http http = new Http();
     HTTPResponse res = http.send(req);
     System.debug(res.getBody());
     Blob faxImage = res.getBodyAsBlob();
     String filePDF;
     Integer resStatus = res.getStatusCode();
        if(resStatus == 200) {
            //ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM, 'Fax sent succesfully.'));
            //this.listInboundFaxes = InterFaxJSON.parseInboundFaxDetail(res.getBody());
            //system.debug('size: '+listOutboundFaxes.size());'
            system.debug('TransactionID: ' + messageId);
            try{
                pdfPreview = EncodingUtil.base64Encode(faxImage);
                faxViewer = true;
            }
            catch(System.DMLException e) {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Error occurred while retrieving Fax.'));
                faxViewer = false;
            }
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Info, 'Fax successfully retrieved'));
        } else {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Error occurred while retrieving Fax. HTTP Status Code: ' + resStatus +' MessageID: '+ this.messageId));
                faxViewer = false;
        }
        
    }
    
         public PageReference LaunchFaxViewer() {
             getRenderPDF();
             PageReference pageRef = new PageReference('/apex/ViewPDF');
             pageRef.setRedirect(true);
             return pageRef;
             }
    
         public void fetchOutboundFaxes() { 
        System.debug('In fetchInboundFaxes:');
        
        HttpRequest req = new HttpRequest();
     req.setEndpoint('https://rest.interfax.net/outbound/faxes');
     req.setMethod('GET');

  Blob headerValue = Blob.valueOf(username + ':' + password);
     String authorizationHeader = 'Basic ' +
     EncodingUtil.base64Encode(headerValue);
     req.setHeader('Authorization', authorizationHeader);
        
     // Create a new http object to send the request object
     // A response object is generated as a result of the request  
  
     Http http = new Http();
     HTTPResponse res = http.send(req);
     System.debug(res.getBody());
     Integer resStatus = res.getStatusCode();
        if(resStatus == 200) {
            //ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM, 'Fax sent succesfully.'));
            this.listOutboundFaxes = InterFaxJSON.parseOutboundFaxDetail(res.getBody());
            system.debug('size: '+listOutboundFaxes.size());
        } else {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Error occurred while fetching sent fax details. HTTP Status: '+resStatus));
        }
    }
}