package qa.gov.moi.erp.web.dmi;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import qa.gov.moi.erp.util.dto.UserDTO;
import qa.gov.moi.erp.util.exceptions.ERPException;
import qa.gov.moi.erp.util.helpers.ERPUtility;

import com.isomorphic.datasource.DSRequest;
import com.isomorphic.datasource.DSResponse;
import com.moi.archive.fn.DocumentBuilderServiceLocator;

public class ComponentAttachmentDMI
{

    private Logger log = LoggerFactory.getLogger(ComponentAttachmentDMI.class);

    public DSResponse fetch(DSRequest dsRequest) throws Exception
    {
        DSResponse response = null;
        String methodName = Thread.currentThread().getStackTrace()[2].getMethodName();
        try
        {
            if (dsRequest.getCriteriaValue("JK3_ID") != null)
            {
                dsRequest.addToCriteria("JK8_MID",dsRequest.getCriteriaValue("JK3_ID"));
            }
            response = dsRequest.execute();

            if (response.getRecords().size() > 0)
            {
                List<Map<String, Object>> records = (List<Map<String, Object>>)response.getRecords();
                for (Map<String, Object> record : records)
                {
                    byte img[] = new DocumentBuilderServiceLocator().getDocumentBuilderPort().retrieveDocument("abc","jsadkf","asdfsad",
                            ((String)record.get("JK8_ATTACHMENT_FILENAME")));
                    InputStream imgInputStream = new ByteArrayInputStream(img);

                    record.put("JK8_ATTACHMENT1",imgInputStream);
                    record.put("JK8_ATTACHMENT1_filename",record.get("JK8_ATTACHMENT_LOCATION"));
                    // record.put("JK8_ATTACHMENT1_filesize",record.get("JK8_ATTACHMENT_filesize"));
                    // record.put("JK8_ATTACHMENT1_date_created",record.get("JK8_ATTACHMENT1_date_created"));
                }

                response.setData(records);
            }
        }
        catch (SQLException e)
        {
            log.error(e.getErrorCode() + "",e);
            throw new ERPException(ERPUtility.formatError(this.getClass().getName(),methodName,e.getErrorCode(),e.getMessage()));
        }
        catch (Exception e)
        {
            log.error(e.getMessage(),e);
            throw new ERPException(ERPUtility.formatError(this.getClass().getName(),methodName,e.getMessage()));
        }
        return response;
    }

    public DSResponse add(DSRequest dsRequest, HttpServletRequest request) throws Exception
    {
        DSResponse response = null;
        String methodName = Thread.currentThread().getStackTrace()[2].getMethodName();
        try
        {
            String uuid = UUID.randomUUID().toString().replaceAll("-","");

            Date date = new Date();
            Timestamp currentTimeStamp = new Timestamp(date.getTime());
            UserDTO userDTO = (UserDTO)dsRequest.getHttpServletRequest().getSession().getAttribute("user");
            dsRequest.setFieldValue("JK8_CREATED_USER_ID",userDTO.getName());
            dsRequest.setFieldValue("JK8_CREATED_USER_ROLE",userDTO.getCurrentRole().getName());
            dsRequest.setFieldValue("JK8_CREATED_USER_SMP",currentTimeStamp);
            dsRequest.setFieldValue("JK8_LASTUPDATED_USER_ID",userDTO.getName());
            dsRequest.setFieldValue("JK8_LASTUPDATED_USER_ROLE",userDTO.getCurrentRole().getName());
            dsRequest.setFieldValue("JK8_LASTUPDATED_USER_SMP",currentTimeStamp);

            if (dsRequest.getFieldValue("ParentPrimayKey1") != null)
            {
                dsRequest.setFieldValue("JK8_MID",dsRequest.getFieldValue("ParentPrimayKey1"));
            }
            if (request.getSession().getAttribute("JK3_ID") != null)
            {
                dsRequest.setFieldValue("JK8_MID",(String)request.getSession().getAttribute("JK3_ID"));
            }
            dsRequest.setFieldValue("JK8_ID",uuid);

            String productId = (String)dsRequest.getFieldValue("JK8_MID");

            String props[] =
            { "ProductID" };
            String vals[] =
            { productId };

            String docID = "";/*-new DocumentBuilderServiceLocator().getDocumentBuilderPort().createDocument("officec16","moi@12345","os01","ERPFileStore",
                              dsRequest.getUploadedFile("JK8_ATTACHMENT1").getFileName(),props,vals,"png",dsRequest.getUploadedFile("JK8_ATTACHMENT1").get());
                              log.info("Added the attachment as " + docID + " >> " + docID);
                               */
            dsRequest.setFieldValue("JK8_ATTACHMENT_FILENAME",docID);
            dsRequest.setFieldValue("JK8_ATTACHMENT_LOCATION",dsRequest.getFieldValue("JK8_ATTACHMENT1_filename"));

            response = dsRequest.execute();
        }
        catch (SQLException e)
        {
            log.error("Exception while adding Component Version",e);
            throw new ERPException(ERPUtility.formatError(this.getClass().getName(),methodName,e.getErrorCode(),e.getMessage()));
        }
        catch (Exception e)
        {
            log.error("Exception while adding  Component Version",e);
            throw new ERPException(ERPUtility.formatError(this.getClass().getName(),methodName,e.getMessage()));
        }
        return response;
    }

    public DSResponse downloadFile(DSRequest dsRequest) throws Exception
    {
        DSResponse response = null;
        String methodName = Thread.currentThread().getStackTrace()[2].getMethodName();
        try
        {

            response = dsRequest.execute();

            byte img[] = new DocumentBuilderServiceLocator().getDocumentBuilderPort().retrieveDocument("abc","jsadkf","asdfsad",
                            ((String)record.get("JK8_ATTACHMENT_FILENAME")));
            InputStream imgInputStream = new ByteArrayInputStream(img);

            Map<String, Object> valuesMap = new HashMap<String, Object>();
            valuesMap.put("JK8_ATTACHMENT1_filename",((String)response.getFieldValue("JK8_ATTACHMENT_LOCATION")));
            valuesMap.put("JK8_ATTACHMENT1",imgInputStream);
            response.setData(valuesMap);

        }
        catch (SQLException e)
        {
            log.error(e.getErrorCode() + "",e);
            throw new ERPException(ERPUtility.formatError(this.getClass().getName(),methodName,e.getErrorCode(),e.getMessage()));
        }
        catch (Exception e)
        {
            log.error(e.getMessage(),e);
            throw new ERPException(ERPUtility.formatError(this.getClass().getName(),methodName,e.getMessage()));
        }
        return response;
    }

    public DSResponse viewFile(DSRequest dsRequest) throws Exception
    {
        DSResponse response = null;
        String methodName = Thread.currentThread().getStackTrace()[2].getMethodName();
        try
        {
            response = dsRequest.execute();

            byte img[] = new DocumentBuilderServiceLocator().getDocumentBuilderPort().retrieveDocument("abc","jsadkf","asdfsad",
                            ((String)record.get("JK8_ATTACHMENT_FILENAME")));
            InputStream imgInputStream = new ByteArrayInputStream(img);

            Map<String, Object> valuesMap = new HashMap<String, Object>();
            valuesMap.put("JK8_ATTACHMENT1_filename",((String)response.getFieldValue("JK8_ATTACHMENT_LOCATION")));
            valuesMap.put("JK8_ATTACHMENT1",imgInputStream);

            response.setData(valuesMap);
        }
        catch (SQLException e)
        {
            log.error(e.getErrorCode() + "",e);
            throw new ERPException(ERPUtility.formatError(this.getClass().getName(),methodName,e.getErrorCode(),e.getMessage()));
        }
        catch (Exception e)
        {
            log.error(e.getMessage(),e);
            throw new ERPException(ERPUtility.formatError(this.getClass().getName(),methodName,e.getMessage()));
        }
        return response;
    }
}
