/// <summary>
        /// 
        /// </summary>
        /// <param name="idReport"></param>
        /// <param name="docToSignPathFileName"></param>
        /// <returns>The url to access the signature page</returns>
        public static string SignReportByCustomer(Guid idReport, string docToSignPathFileName, int pageCount)
        {
            using (UpsilabEntities context = new UpsilabEntities())
            {
                Upsilab.Data.Model.Report report = (from rep in context.Report.Include("CustomerProspect")
                                                    where rep.idReport == idReport
                                                    select rep).FirstOrDefault();

                if (report == null)
                {
                    throw new Exception(LanguageContentBL.Translate("signature_select_doc"));
                }

                // Check if already signed by customer
                if (report.SignedByCustomer)
                {
                    throw new Exception(LanguageContentBL.Translate("signature_doc_signed_by_customer"));
                }

                // Check if Firm has sufficient credit to send doc to coffre fort
                

                // Data needed
                string businessId = string.Format("{0}-{1}", REPORT, idReport);
                Upsilab.Data.Model.CustomerProspect customer = report.CustomerProspect;
                string backUrl = string.Format("{0}/Client/Signature/RetourSignatureRecueilParClient{1}", Upsilab.Business.Utility.UrlHelper.GetHost(), DTPClient.GET_Variables);

                bool isPP = (customer.IsCorporation.HasValue) ? ((customer.IsCorporation.Value) ? false : true) : false;
                
                List<SignatureParameter> signatureParameters = new List<SignatureParameter>();

                SignatureParameter signatureParameter = new SignatureParameter()
                {
                    SignatureFieldLabel = DTPClient.USER_ADVISER,
                    SignaturePosition = new SignaturePosition(pageCount, true)
                };

                signatureParameters.Add(signatureParameter);

                signatureParameter = new SignatureParameter()
                {
                    SignatureFieldLabel = DTPClient.USER_CUSTOMER,
                    SignaturePosition = new SignaturePosition(pageCount, false)
                };

                signatureParameters.Add(signatureParameter);

                //Document to sign
                DocumentToSign doc = new DocumentToSign()
                {
                    Label = LanguageContentBL.Translate("signature_report_title"),
                    Description = LanguageContentBL.Translate("signature_report_title"),
                    PathFilename = docToSignPathFileName,
                    Type = DTPClient.DocumentTypes.CONTRACT.ToString(),
                    SignatureParameters = signatureParameters
                };

                List<DocumentToSign> documentsToSign = new List<DocumentToSign>() { doc };

                //DTP Data
                DTPData dtpData = new DTPData()
                {
                    TransactionId = report.idDictao,
                    UserAccessId = report.idDTPUserAccess,
                    BusinessId = businessId,
                    BackUrl = backUrl,
                    DocumentsToSign = documentsToSign,
                    SignatureFieldLabels = new List<string>() { DTPClient.USER_CUSTOMER },
                    UserSpaceTitle = LanguageContentBL.Translate("signature_report_sign_title"),
                    Language = SessionManager.GetCurrentLanguage().LanguageTypeName,
                };

                // Check if already signed by adviser, if not, the customer signs the doc first.
                if (!report.SignedByAdviser)
                {                    
                    //Sign document
                    dtpData = SignatureDocumentBL.SignByFirstUser(customer.User, dtpData);

                    //Save transaction Id to table
                    report.idDictao = dtpData.TransactionId;
                    report.idDTPUserAccess = dtpData.UserAccessId;
                }
                else
                {
                    dtpData = SignatureDocumentBL.SignBySecondUser(customer.User, dtpData);
                    
                    //Save userAccess Id to table                    
                    report.idDTPUserAccess = dtpData.UserAccessId;
                }

                context.SaveChanges();

                return dtpData.IHM_Url;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="idReport"></param>
        /// <returns>The url to access the signature page</returns>
        public static string SignConfidentialityAgreementByAdviser(Guid idCustomer, string docToSignPathFileName, Upsilab.Data.Model.User userAdviser)
        {
            using (UpsilabEntities context = new UpsilabEntities())
            {
                Upsilab.Data.Model.CustomerProspect customer = (from cust in context.CustomerProspect.Include("ConfidentialityAgreement").Include("User").Include("User1")
                                                                where cust.idCustomer == idCustomer
                                                                select cust).FirstOrDefault();

                if (customer == null)
                {
                    throw new Exception(LanguageContentBL.Translate("signature_select_customer"));
                }

                Upsilab.Data.Model.ConfidentialityAgreement confident = customer.ConfidentialityAgreement;

                if (confident == null)
                {
                    confident = new Upsilab.Data.Model.ConfidentialityAgreement()
                    {
                        idConfidentialityAgreement = Upsilab.Business.Utility.GuidHelper.GenerateGuid(),
                        Status = ReportBL.Status.InProgress.ToString(),
                        DateCreated = DateTime.Now,
                        SignedByCustomer = false,
                        SignedByAdviser = false,
                        Archived = false
                    };

                    context.ConfidentialityAgreement.Attach(confident);
                    context.ObjectStateManager.ChangeObjectState(confident, System.Data.EntityState.Added);

                    customer.idConfidentialityAgreement = confident.idConfidentialityAgreement;
                }

                //Check if already signed by adviser
                if (confident.SignedByAdviser)
                {
                    throw new Exception(LanguageContentBL.Translate("signature_ec_signed"));
                }

                // Data needed
                string businessId = string.Format("{0}-{1}", CONFIDENTIALITY_AGREEMENT, idCustomer);
                string backUrl = string.Format("{0}/User/Signature/RetourSignatureEngagementParConseiller{1}", Upsilab.Business.Utility.UrlHelper.GetHost(), DTPClient.GET_Variables);

                List<SignatureParameter> signatureParameters = new List<SignatureParameter>();

                SignatureParameter signatureParameter = new SignatureParameter()
                {
                    SignatureFieldLabel = DTPClient.USER_ADVISER,

                    SignaturePosition = new SignaturePosition()
                    {
                        Page = 8,
                        X = 28,
                        Y = 85,
                    }
                };

                signatureParameters.Add(signatureParameter);

                signatureParameter = new SignatureParameter()
                {
                    SignatureFieldLabel = DTPClient.USER_CUSTOMER,

                    SignaturePosition = new SignaturePosition()
                    {
                        Page = 8,
                        X = 114,
                        Y = 85,
                    }
                };

                signatureParameters.Add(signatureParameter);

                //Document to sign
                DocumentToSign doc = new DocumentToSign()
                {
                    Label = LanguageContentBL.Translate("signature_ec_title"),
                    Description = LanguageContentBL.Translate("signature_ec_title"),
                    PathFilename = docToSignPathFileName,
                    Type = DTPClient.DocumentTypes.CONTRACT.ToString(),
                    SignatureParameters = signatureParameters
                };

                List<DocumentToSign> documentsToSign = new List<DocumentToSign>() { doc };

                //DTP Data
                DTPData dtpData = new DTPData()
                {
                    TransactionId = confident.idDictao,
                    UserAccessId = confident.idDTPUserAccess,
                    BusinessId = businessId,
                    BackUrl = backUrl,
                    DocumentsToSign = documentsToSign,
                    SignatureFieldLabels = new List<string> { DTPClient.USER_ADVISER },
                    UserSpaceTitle = LanguageContentBL.Translate("signature_ec_sign_title"),
                    Language = SessionManager.GetCurrentLanguage().LanguageTypeName,
                };

                // Check if already signed by customer, if not, the adviser signs the doc first.
                if (!confident.SignedByCustomer)
                {
                    //Sign document
                    dtpData = SignatureDocumentBL.SignByFirstUser(userAdviser, dtpData);

                    //Save transaction Id to table
                    confident.idDictao = dtpData.TransactionId;
                    confident.idDTPUserAccess = dtpData.UserAccessId;
                }
                else
                {
                    dtpData = SignatureDocumentBL.SignBySecondUser(userAdviser, dtpData);

                    confident.idDTPUserAccess = dtpData.UserAccessId;
                }

                context.SaveChanges();

                return dtpData.IHM_Url;
            }
        }
        public static string SignDocument(Guid idSignatory)
        {
            using (UpsilabEntities db = new UpsilabEntities())
            {
                var currentSignatory = (from sign in db.Signatory//.Include("User")
                                        where sign.idSignatory == idSignatory
                                        select sign).FirstOrDefault();

                var lstFieldLabelsCurrentSignatory = new List<string>();

                if (currentSignatory == null)
                {
                    throw new Exception(LanguageContentBL.Translate("signature_not_allowed_to_sign"));
                }

                // Check if already signed by user
                if (currentSignatory.DateSignature.HasValue)
                {
                    throw new Exception(string.Format(LanguageContentBL.Translate("signature_doc_signed_on"), currentSignatory.DateSignature.Value.ToShortDateString()));
                }

                //Liste des signataires
                SignatureTransaction signatureTransaction = (from signTrans in db.SignatureTransaction
                                                                                //.Include("Signatory")
                                                                                //.Include("Document")
                                                                                //.Include("Document.DocumentSignatory")
                                                                                //.Include("Document.DocumentModel")
                                                                  where signTrans.idSignatureTransaction == currentSignatory.idSignatureTransaction
                                                                  select signTrans).FirstOrDefault();
              
                // Data needed
                //1- Business Id
                string businessId = string.Format("{0}-{1}", DOCUMENT, currentSignatory.idSignatureTransaction);
                
                //2- back Url
                string backUrl = string.Format("{0}/Signature/RetourSignatureDocument{1}", Upsilab.Business.Utility.UrlHelper.GetSiteUrl(), DTPClient.GET_Variables); //TODO : User ??
                
                //3- List of documents to sign
                var documentsToSign = new List<DocumentToSign>();

                // Document different from documentType = DOC (This type of document is only to send to "coffre fort" not to sign)
                // And document which have config signatory : page, x, y...
                var docDocType = ElectronicSafeDocumentBL.DocumentType.DOC.ToString();

                var documents = (from doc in signatureTransaction.Document
                                 where doc.DocumentType != docDocType && doc.DocumentSignatory.Count > 0
                                 select doc).ToList();

                //TODO : TEST-------------------------------------
                //documents = documents.Where(x => x.DocumentType == "CPART").ToList();
                //FIN TEST----------------------------------------

                // Check if there is a document to sign
                if (documents.Count == 0)
                {
                    throw new Exception(LanguageContentBL.Translate("signature_no_doc"));
                }

                for (int i = 0; i < documents.Count; i++)
                {
                    List<SignatureParameter> signatureParameters = new List<SignatureParameter>();
                    bool isSignParamsFromFile = false;
                    var document = documents.ElementAt(i);
                    var documentModel = document.DocumentModel;

                    if (document.GeneratedFromModel) //Doc generated from model
                    {
                        //Dans certains cas, les parametres de signature sont donnés sur un fichier json par rapport au modele de document
                        if (documentModel != null)
                        {
                            var jsonSignParams = Upsilab.Business.Sdg.DocumentModelFileBL.GetSignatureParametersContentFromFile(documentModel);
                            signatureParameters = SignatureParameter.JsonToSignatureParameters(jsonSignParams);

                            if (signatureParameters.Count > 0)
                            {
                                isSignParamsFromFile = true;
                            }
                        }
                    }

                    //Position de la zone de signature de chaque signataire sur le document
                    foreach (var signataire in signatureTransaction.Signatory)
                    {

                        //Signature fieldLabel
                        var signatureFieldLabel = string.Format("{0}-{1}", DTPClient.USER, signataire.idSignatory);

                        if (isSignParamsFromFile) //just update "SignatureFieldLabel"
                        {
                            var signatoryRole = signataire.Role;
                            var j = 0;
                            signatureParameters.Where(sp => sp.SignatoryRole == signatoryRole).ToList().ForEach(sp =>
                                {
                                    //Differencier par un compteur les fieldLabes
                                    sp.SignatureFieldLabel = string.Format("{0}-{1}", signatureFieldLabel, j);
                                    j++;
                                });
                        }
                        else //Create the signatureParameter //TODO : if many fields for defined manually
                        {
                            var documentSignatories = signataire.DocumentSignatory.Where(ds => ds.idDocument == document.idDocument).ToList(); //Liste des zones de signature du signataire
                            var j = 0;

                            documentSignatories.ForEach(documentSignatory =>
                            {
                                var x = documentSignatory.X;
                                var y = documentSignatory.Y;
                                var height = documentSignatory.Height;
                                var width = documentSignatory.Width;

                                //NB : les valeurs provenant de la BD est en "pixel", convertir en "mm" pour dictao ? 
                                //=> pour les documents dont on a defini manuellement les zones
                                //=> pas de conversion pour les documents automatiques
                                if (!document.GeneratedFromModel) //zones de signature definies manuellement
                                {
                                    x = ConverPixelToMillimeter(x);
                                    y = 297 - ConverPixelToMillimeter(height) - ConverPixelToMillimeter(y); //297 <=> height A4 ?
                                    width = ConverPixelToMillimeter(width);
                                    height = ConverPixelToMillimeter(height);
                                }

                                SignatureParameter signatureParameter = new SignatureParameter()
                                {
                                    //SignatureFieldLabel = signatureFieldLabel,
                                    SignatureFieldLabel = string.Format("{0}-{1}", signatureFieldLabel, j),
                                    SignatoryRole = signataire.Role,

                                    SignaturePosition = new SignaturePosition()
                                    {
                                        Page = documentSignatory.Page,
                                        X = x,
                                        Y = y,
                                        Width = width,
                                        Height = height
                                    }
                                };

                                signatureParameters.Add(signatureParameter);
                                j++;
                            }
                            );
                        }

                    }
                    

                    //Document to sign
                    string dtpDocType = (i == 0) ? DTPClient.DocumentTypes.CONTRACT.ToString() : string.Format("{0}{1}", DTPClient.APPENDIX, i);

                    //Label of the document to send to DICTAO ?
                    //Particular case for AVENANT : get the document name
                    var label = (string.IsNullOrEmpty(document.Status)) ? LanguageContentBL.Translate("signature_doc_title") : LanguageContentBL.Translate(document.DocumentType.ToLower());

                    var avenantDocumentTypes = DocumentSignatureTransactionBL.GetDocumentTypes(DocumentSignatureTransactionBL.SignatureTransactionType.AVENANT);

                    if (avenantDocumentTypes.Contains(document.DocumentType))
                    {
                        label = document.Designation;
                    }
                  
                    DocumentToSign doc = new DocumentToSign()
                    {
                        Label = label,
                        Description = label,
                        PathFilename = FileManager.GetFileFromUploadDirectory(document.Location, document.Name),
                        Type = dtpDocType,
                        SignatureParameters = signatureParameters
                    };

                    documentsToSign.Add(doc);

                    //List des signatureFields for currentSignatory
                    signatureParameters.ForEach(sp => 
                    {
                        if (sp.SignatoryRole == currentSignatory.Role)
                        {
                            if (!lstFieldLabelsCurrentSignatory.Contains(sp.SignatureFieldLabel))
                            {
                                lstFieldLabelsCurrentSignatory.Add(sp.SignatureFieldLabel);
                            }
                        }
                    });

                }
                                                
                //DTP Data
                DTPData dtpData = new DTPData()
                {
                    TransactionId = currentSignatory.SignatureTransaction.idDTPTransaction,
                    UserAccessId = currentSignatory.idDTPUserAccess,
                    BusinessId = businessId,
                    BackUrl = backUrl,
                    DocumentsToSign = documentsToSign,
                    SignatureFieldLabels = lstFieldLabelsCurrentSignatory,//new List<string> { string.Format("{0}-{1}", DTPClient.USER, currentSignatory.idSignatory) }, //Exemple : USER-00000-00000-...
                    SignatureRole = currentSignatory.Role,
                    UserSpaceTitle = LanguageContentBL.Translate("signature_doc_sign_title"),
                    Language = SessionManager.GetCurrentLanguage().LanguageTypeName,
                };

               //User info ?
                var user = currentSignatory.User;
                if (user == null)
                {
                    user = new Data.Model.User()
                    {
                        UserName = currentSignatory.Name,
                        UserFirstName = !string.IsNullOrEmpty(currentSignatory.Firstname) ? currentSignatory.Firstname : " ", //TODO : test
                        UserMobilePhone = currentSignatory.Mobile,
                        UserEmail = currentSignatory.Email,

                        idUser = Guid.Empty,
                        idUserProfile = 7,
                        UserPassword = string.Empty,
                        DateCreated = DateTime.Now,
                    };
                }

                // Check if any users has signed first. if not, he signs first
                var anySignatoryHasSigned = signatureTransaction.Signatory.Where(sign => sign.DateSignature.HasValue).FirstOrDefault();

                if (anySignatoryHasSigned == null)
                {
                    //Sign document
                    dtpData = SignatureDocumentBL.SignByFirstUser(user, dtpData);

                    //Save transaction Id to table
                    signatureTransaction.idDTPTransaction = dtpData.TransactionId;
                    currentSignatory.idDTPUserAccess = dtpData.UserAccessId;
                }
                else
                {
                    dtpData = SignatureDocumentBL.SignBySecondUser(user, dtpData);

                    //Save userAccess Id to table                    
                    currentSignatory.idDTPUserAccess = dtpData.UserAccessId;
                }

                db.SaveChanges();

                return dtpData.IHM_Url;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="idReport"></param>
        /// <returns>The url to access the signature page</returns>
        public static string SignCRTOByAdviser(Guid idCustomer, string docToSignPathFileName, Upsilab.Data.Model.User userAdviser)
        {
            using (UpsilabEntities context = new UpsilabEntities())
            {
                var customer = context.CustomerProspect.FirstOrDefault(x => x.idCustomer == idCustomer);

                //Add new CRTO
                var crto = new Upsilab.Data.Model.ConventionRTO()
                {
                    idConventionRTO = Upsilab.Business.Utility.GuidHelper.GenerateGuid(),
                    IdCustomerProspect = idCustomer,
                    Status = ReportBL.Status.InProgress.ToString(),
                    SignedByCustomer = false,
                    SignedByAdviser = false,
                    Archived = false,
                    DatesSendMailToCustomer = DateTime.Now.ToString("dd/MM/yyyy"),
                    DateCreated = DateTime.Now,
                    DateUpdated = DateTime.Now,
                };

                context.ConventionRTO.Attach(crto);
                context.ObjectStateManager.ChangeObjectState(crto, System.Data.EntityState.Added);

                //Update idConvention customer
                customer.idConventionRTO = crto.idConventionRTO;

                // Data needed
                string businessId = string.Format("{0}-{1}", CONVENTION_RTO, idCustomer);
                string backUrl = string.Format("{0}/User/Signature/RetourSignatureCRTOParConseiller{1}", Upsilab.Business.Utility.UrlHelper.GetHost(), DTPClient.GET_Variables);

                List<SignatureParameter> signatureParameters = new List<SignatureParameter>();

                SignatureParameter signatureParameter = new SignatureParameter()
                {
                    SignatureFieldLabel = DTPClient.USER_ADVISER,

                    SignaturePosition = new SignaturePosition()
                    {
                        Page = 4, //TODO
                        X = 34,
                        Y = 178,
                    }
                };

                signatureParameters.Add(signatureParameter);

                signatureParameter = new SignatureParameter()
                {
                    SignatureFieldLabel = DTPClient.USER_CUSTOMER,

                    SignaturePosition = new SignaturePosition()
                    {
                        Page = 4, //TODO
                        X = 120,
                        Y = 178,
                    }
                };

                signatureParameters.Add(signatureParameter);

                //Document to sign
                DocumentToSign doc = new DocumentToSign()
                {
                    Label = LanguageContentBL.Translate("signature_crto_title"),
                    Description = LanguageContentBL.Translate("signature_crto_title"),
                    PathFilename = docToSignPathFileName,
                    Type = DTPClient.DocumentTypes.CONTRACT.ToString(),
                    SignatureParameters = signatureParameters
                };

                List<DocumentToSign> documentsToSign = new List<DocumentToSign>() { doc };

                //DTP Data
                DTPData dtpData = new DTPData()
                {
                    TransactionId = crto.idDictao,
                    UserAccessId = crto.idDTPUserAccess,
                    BusinessId = businessId,
                    BackUrl = backUrl,
                    DocumentsToSign = documentsToSign,
                    SignatureFieldLabels = new List<string> { DTPClient.USER_ADVISER },
                    UserSpaceTitle = LanguageContentBL.Translate("signature_crto_sign_title"),
                    Language = SessionManager.GetCurrentLanguage().LanguageTypeName,
                };

                //Sign document :  adviser always sign first
                dtpData = SignatureDocumentBL.SignByFirstUser(userAdviser, dtpData);

                //Save transaction Id to table
                crto.idDictao = dtpData.TransactionId;
                crto.idDTPUserAccess = dtpData.UserAccessId;

                context.SaveChanges();

                return dtpData.IHM_Url;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="idCustomer"></param>
        /// <param name="docToSignPathFileName"></param>
        /// <returns>The url to access the signature page</returns>
        public static string SignCRTOByCustomer(Guid idCustomer)
        {
            using (UpsilabEntities context = new UpsilabEntities())
            {
                var latestCRTO = (from crto in context.ConventionRTO.Include("CustomerProspect_1.User")
                                 where crto.IdCustomerProspect == idCustomer && crto.SignedByAdviser && !crto.Archived
                                 orderby crto.DateUpdated descending
                                 select crto).FirstOrDefault();

                if (latestCRTO == null)
                {
                    throw new Exception(LanguageContentBL.Translate("signature_select_customer"));
                }

                // Check if already signed by customer
                if (latestCRTO.SignedByCustomer)
                {
                    throw new Exception(LanguageContentBL.Translate("signature_crto_signed"));
                }

                // Data needed
                string businessId = string.Format("{0}-{1}", CONVENTION_RTO, latestCRTO.idConventionRTO);
                string backUrl = string.Format("{0}/Client/Signature/RetourSignatureCRTOParClient{1}", Upsilab.Business.Utility.UrlHelper.GetHost(), DTPClient.GET_Variables);

                List<SignatureParameter> signatureParameters = new List<SignatureParameter>();

                //Document to sign
                DocumentToSign doc = new DocumentToSign()
                {
                    Label = LanguageContentBL.Translate("signature_crto_title"),
                    Description = LanguageContentBL.Translate("signature_crto_title"),
                    //PathFilename = docToSignPathFileName,
                    Type = DTPClient.DocumentTypes.CONTRACT.ToString(),
                    SignatureParameters = signatureParameters
                };

                List<DocumentToSign> documentsToSign = new List<DocumentToSign>() { doc };

                //DTP Data
                DTPData dtpData = new DTPData()
                {
                    TransactionId = latestCRTO.idDictao,
                    UserAccessId = latestCRTO.idDTPUserAccess,
                    BusinessId = businessId,
                    BackUrl = backUrl,
                    DocumentsToSign = documentsToSign,
                    SignatureFieldLabels = new List<string> { DTPClient.USER_CUSTOMER },
                    UserSpaceTitle = LanguageContentBL.Translate("signature_crto_sign_title"),
                    Language = SessionManager.GetCurrentLanguage().LanguageTypeName,
                };

                // CRTO is signed secondly by customer
                dtpData = SignatureDocumentBL.SignBySecondUser(latestCRTO.CustomerProspect_1.User, dtpData);
                latestCRTO.idDTPUserAccess = dtpData.UserAccessId;
                
                context.SaveChanges();

                return dtpData.IHM_Url;
            }
        }
        private List<DocumentToSign> GetDocumentsToSign(DER der)
        {
            string error = string.Empty;
            int pageCount = 0;
            CustomerProspect customer = der.CustomerProspect;
            List<DocumentToSign> documentsToSign = new List<DocumentToSign>();


            #region 1- Fiche d'information legale FIL => DER
                    List<SignatureParameter> signatureParametersDER = new List<SignatureParameter>();
                    //A- PDF ?
                    pageCount = 0;
                    string docType = ElectronicSafeDocumentBL.DocumentType.FIL.ToString();
                    string firmDocumentPath = string.Format(@"{0}\FirmInstitution\FI_{1}", Server.MapPath("~/uploads"), der.CustomerProspect.FirmInstitution.idFirmInstitution);
                    string destFullPath = ElectronicSafeDocumentBL.BuildClientUploadDocumentPath(docType, customer);
                    string filename = ElectronicSafeDocumentBL.BuildDocumentName(docType, der.idDer, false);

                    string destFILFilePath = System.IO.Path.Combine(destFullPath, filename);

                    //From firmModel or from upsideomodel
                    if (der.IsDerFromModel)
                    {
                        //Merge pdf
                        filename = der.CustomerProspect.FirmInstitution.LegalInformationFile;
                        string uploadedDoc = System.IO.Path.Combine(firmDocumentPath, filename);

                        if (System.IO.File.Exists(uploadedDoc))
                        {
                            Upsilab.Business.Configuration.FirmInstitutionPdfGeneration.GenerateDERByMerge(der.CustomerProspect.FirmInstitution, uploadedDoc, destFILFilePath, false, out pageCount);
                        }
                        else
                        {
                            error = _languageData.GetContent("le_pdf_doc_entree_en_relation_n_existe_pas");
                        }

                    }
                    else
                    {
                        //From upsideo model => generate it
                        pageCount = Upsilab.Business.Configuration.FirmInstitutionPdfGeneration.GenerateDER(der.CustomerProspect.FirmInstitution, der.CustomerProspect.idCustomer, destFILFilePath, false);
                    }

                    if (!System.IO.File.Exists(destFILFilePath))
                    {
                        error = _languageData.GetContent("le_pdf_doc_entree_en_relation_n_existe_pas");
                    }
                    else
                    {
                        //B- Prepare object to send to signature
                        SignatureParameter signatureParameter = new SignatureParameter()
                        {
                            SignatureFieldLabel = DTPClient.USER_ADVISER,

                            SignaturePosition = new SignaturePosition()
                            {
                                Page = (pageCount > 0) ? pageCount : 16, //DER : 16pages
                                X = 33,
                                Y = 177
                            }
                        };

                        signatureParametersDER.Add(signatureParameter);

                        signatureParameter = new SignatureParameter()
                        {
                            SignatureFieldLabel = DTPClient.USER_CUSTOMER,

                            SignaturePosition = new SignaturePosition()
                            {
                                Page = (pageCount > 0) ? pageCount : 16, //DER : 16pages
                                X = 120,
                                Y = 177
                            }
                        };

                        signatureParametersDER.Add(signatureParameter);

                        DocumentToSign docDER = new DocumentToSign()
                        {
                            Label = _languageData.GetContent("doc_entree_en_relation"),
                            Description = _languageData.GetContent("doc_entree_en_relation"),
                            PathFilename = destFILFilePath,
                            Type = DTPClient.DocumentTypes.CONTRACT.ToString(),
                            SignatureParameters = signatureParametersDER
                        };

                        documentsToSign.Add(docDER);
                    }
                
            
            #endregion

            #region 2- Presentation etablissement
            if (der.AttachPresentation)
            {
                List<SignatureParameter> signatureParametersBS = new List<SignatureParameter>();
                //A- PDF ?
                pageCount = 0;
                docType = ElectronicSafeDocumentBL.DocumentType.BS.ToString();
                firmDocumentPath = string.Format(@"{0}\FirmInstitution\FI_{1}", Server.MapPath("~/uploads"), der.CustomerProspect.FirmInstitution.idFirmInstitution);
                destFullPath = ElectronicSafeDocumentBL.BuildClientUploadDocumentPath(docType, customer);
                filename = ElectronicSafeDocumentBL.BuildDocumentName(docType, der.idDer, false);

                string destBSFilePath = System.IO.Path.Combine(destFullPath, filename);

                //From firmModel or from upsideomodel
                if (der.IsPresentationFromModel)
                {
                    //Merge pdf
                    filename = der.CustomerProspect.FirmInstitution.PresentationFile;
                    string uploadedDoc = System.IO.Path.Combine(firmDocumentPath, filename);

                    if (System.IO.File.Exists(uploadedDoc))
                    {
                        Upsilab.Business.Configuration.FirmInstitutionPdfGeneration.GeneratePresentationByMerge(der.CustomerProspect.FirmInstitution, uploadedDoc, destBSFilePath, false, out pageCount);
                    }
                    else
                    {
                        error = _languageData.GetContent("pdf_presentation_etab_n_existe_pas_ou");
                    }

                }
                else
                {
                    //From upsideo model => generate it
                    Upsilab.Business.Configuration.FirmInstitutionPdfGeneration.GeneratePresentation(der.CustomerProspect.FirmInstitution, destBSFilePath, false);
                }

                if (!System.IO.File.Exists(destBSFilePath))
                {
                    error = _languageData.GetContent("pdf_presentation_etab_n_existe_pas_ou");
                }
                else
                {
                    //B- Prepare object to send to signature
                    SignatureParameter signatureParameter = new SignatureParameter()
                    {
                        SignatureFieldLabel = DTPClient.USER_ADVISER,

                        SignaturePosition = new SignaturePosition()
                        {
                            Page = (pageCount > 0) ? pageCount : 6, //BS : 6pages
                            X = 33,
                            Y = 177
                        }
                    };

                    signatureParametersBS.Add(signatureParameter);

                    signatureParameter = new SignatureParameter()
                    {
                        SignatureFieldLabel = DTPClient.USER_CUSTOMER,

                        SignaturePosition = new SignaturePosition()
                        {
                            Page = (pageCount > 0) ? pageCount : 6, //BS : 6pages
                            X = 120,
                            Y = 177
                        }
                    };

                    signatureParametersBS.Add(signatureParameter);


                    DocumentToSign docPE = new DocumentToSign()
                    {
                        Label = _languageData.GetContent("presentation_de_l_etab"),
                        Description = _languageData.GetContent("presentation_de_l_etab"),
                        PathFilename = destBSFilePath,
                        Type = DTPClient.DocumentTypes.APPENDIX1.ToString(),
                        SignatureParameters = signatureParametersBS
                    };

                    documentsToSign.Add(docPE);
                }
            }
            #endregion

            return documentsToSign;

        }
        private List<DocumentToSign> GetDocumentsToSign(MissionDocument missionDoc)
        {
            var currentUser = SessionManager.GetUserSession();
            string error = string.Empty;
            int pageCount = 0;
            CustomerProspect customer = missionDoc.CustomerProspect;
            bool isPP = (missionDoc.CustomerProspect.IsCorporation.HasValue) ? ((missionDoc.CustomerProspect.IsCorporation.Value) ? false : true) : false;
            List<SignatureParameter> signatureParametersMD = new List<SignatureParameter>();
            List<DocumentToSign> documentsToSign = new List<DocumentToSign>();

            #region 1- Mission document
            //A- Build pdf mission document to sign
            string docType = (missionDoc.IsLetter) ? ElectronicSafeDocumentBL.DocumentType.LM.ToString() : ElectronicSafeDocumentBL.DocumentType.RM.ToString();

            string destFullPath = ElectronicSafeDocumentBL.BuildClientUploadDocumentPath(docType, customer);
            string filename = ElectronicSafeDocumentBL.BuildDocumentName(docType, missionDoc.idMissionDocument, false);

            string destMissionDocFilePath = System.IO.Path.Combine(destFullPath, filename);

            //If Upsideo model, generate pdf
            //If Firm model, merge uploaded file with the first and last page
            if (missionDoc.IsUpsideoModel)
            {
                //1 : Génération du PDF
                if (missionDoc.IsLetter) //Lettre de Mission
                {
                    if (isPP)
                    {
                        pageCount = MissionDocumentPdfGenerationBL.GeneratePP_EngagementLetter(missionDoc, destMissionDocFilePath, false);
                    }
                    else
                    {
                        pageCount = MissionDocumentPdfGenerationBL.GeneratePM_EngagementLetter(missionDoc, destMissionDocFilePath, false);
                    }
                }
                else // Rapport de mission
                {
                    pageCount = MissionDocumentPdfGenerationBL.Generate_MissionReport(missionDoc, destMissionDocFilePath, false);
                }

            }
            else
            {
                //Merge pdf
                filename = missionDoc.FileName;
                string uploadedDoc = System.IO.Path.Combine(destFullPath, filename);
                if (missionDoc.IsLetter)
                {
                    MissionDocumentPdfGenerationBL.GenerateEngagementLetterByMerge(missionDoc, uploadedDoc, destMissionDocFilePath, false, out pageCount);
                }
                else
                {
                    MissionDocumentPdfGenerationBL.GenerateReportLetterByMerge(missionDoc, uploadedDoc, destMissionDocFilePath, false, out pageCount);
                }
            }

            if (!System.IO.File.Exists(destMissionDocFilePath))
            {
                error = _languageData.GetContent("doc_n_a_pas_ete_genere_correctement");
            }
            else
            {
                //B- Prepare object to sign
                SignatureParameter signatureParameter = new SignatureParameter()
                {
                    SignatureFieldLabel = DTPClient.USER_ADVISER,

                    SignaturePosition = new SignaturePosition()
                    {
                        Page = (pageCount > 0) ? pageCount : (missionDoc.IsLetter) ? (isPP ? 13 : 12) : 10, //LM : 13pages; RM : 10pages
                        X = 33,
                        Y = 177
                    }                    
                };

                signatureParametersMD.Add(signatureParameter);

                signatureParameter = new SignatureParameter()
                {
                    SignatureFieldLabel = DTPClient.USER_CUSTOMER,

                    SignaturePosition = new SignaturePosition()
                    {
                        Page = (pageCount > 0) ? pageCount : (missionDoc.IsLetter) ? (isPP ? 13 : 12) : 10, //LM : 13pages; RM : 10pages
                        X = 120,
                        Y = 177
                    }
                };
                
                signatureParametersMD.Add(signatureParameter);

                string typeDocLabel = (missionDoc.IsLetter) ? _languageData.GetContent("lettre_de_mission") : _languageData.GetContent("rapport_de_mission");

                DocumentToSign docMD = new DocumentToSign()
                {
                    Label = typeDocLabel,
                    Description = typeDocLabel,
                    PathFilename = destMissionDocFilePath,
                    Type = DTPClient.DocumentTypes.CONTRACT.ToString(),
                    SignatureParameters = signatureParametersMD
                };

                documentsToSign.Add(docMD);
            }
            #endregion

            #region 2- Convention RTO Document
            if (missionDoc.AttachConventionRTO.HasValue && missionDoc.AttachConventionRTO.Value)
            {
                List<SignatureParameter> signatureParametersRTO = new List<SignatureParameter>();
                //A- Generate CRTO pdf
                pageCount = 0;
                docType = (missionDoc.IsLetter) ? ElectronicSafeDocumentBL.DocumentType.LM.ToString() : ElectronicSafeDocumentBL.DocumentType.RM.ToString();
                docType = docType + "_" + ElectronicSafeDocumentBL.DocumentType.CRTO.ToString();

                destFullPath = ElectronicSafeDocumentBL.BuildClientUploadDocumentPath(docType, customer);
                filename = ElectronicSafeDocumentBL.BuildDocumentName(docType, missionDoc.idMissionDocument, false);

                string destCRTOFilePath = System.IO.Path.Combine(destFullPath, filename);

                //If Upsideo model, generate pdf
                //If Firm model, merge uploaded file with the first and last page
                if (missionDoc.IsConventionRTOFromYourModel.HasValue && !missionDoc.IsConventionRTOFromYourModel.Value)
                {
                    //MissionDocumentPdfGenerationBL.GenerateRTO(missionDoc, destCRTOFilePath, false);
                    pageCount = MissionDocumentPdfGenerationBL.GenerateRTO(missionDoc.idMissionDocument, missionDoc.User,
                                                               missionDoc.CustomerProspect, destCRTOFilePath, false);
                }
                else if (!string.IsNullOrEmpty(missionDoc.ConventionRTOFirmModelFileName))
                {
                    //Merge pdf
                    filename = missionDoc.ConventionRTOFirmModelFileName;
                    string uploadedDoc = System.IO.Path.Combine(destFullPath, filename);

                    MissionDocumentPdfGenerationBL.GenerateRTOByMerge(missionDoc, uploadedDoc, destCRTOFilePath, false, out pageCount);
                }

                if (!System.IO.File.Exists(destCRTOFilePath))
                {
                    error = _languageData.GetContent("pdf_rto_n_a_pas_ete_genere_correctement");
                }
                else
                {
                    //B- Prepare object to send to signature
                    SignatureParameter signatureParameter = new SignatureParameter()
                    {
                        SignatureFieldLabel = DTPClient.USER_ADVISER,

                        SignaturePosition = new SignaturePosition()
                        {
                            Page = (pageCount > 0) ? pageCount : 4, //CRTO : 4pages
                            X = 33,
                            Y = 177
                        }
                    };

                    signatureParametersRTO.Add(signatureParameter);

                    signatureParameter = new SignatureParameter()
                    {
                        SignatureFieldLabel = DTPClient.USER_CUSTOMER,

                        SignaturePosition = new SignaturePosition()
                        {
                            Page = (pageCount > 0) ? pageCount : 4, //CRTO : 4pages
                            X = 120,
                            Y = 177
                        }
                    };

                    signatureParametersRTO.Add(signatureParameter);


                    DocumentToSign docRTO = new DocumentToSign()
                    {
                        Label = _languageData.GetContent("convention_de_rto"),
                        Description = _languageData.GetContent("convention_de_rto"),
                        PathFilename = destCRTOFilePath,
                        Type = DTPClient.DocumentTypes.APPENDIX3.ToString(),
                        SignatureParameters = signatureParametersRTO
                    };

                    documentsToSign.Add(docRTO);
                }
            }
            #endregion

            #region 3- Presentation etablissement
            if (missionDoc.AttachPresentation)
            {
                List<SignatureParameter> signatureParametersBS = new List<SignatureParameter>();
                //A- PDF ?
                pageCount = 0;
                docType = ElectronicSafeDocumentBL.DocumentType.BS.ToString();
                string firmDocumentPath = string.Format(@"{0}\FirmInstitution\FI_{1}", Server.MapPath("~/uploads"), missionDoc.CustomerProspect.FirmInstitution.idFirmInstitution);
                destFullPath = ElectronicSafeDocumentBL.BuildClientUploadDocumentPath(docType, customer);
                filename = ElectronicSafeDocumentBL.BuildDocumentName(docType, missionDoc.idMissionDocument, false);

                string destBSFilePath = System.IO.Path.Combine(destFullPath, filename);

                //From firmModel or from upsideomodel
                if (missionDoc.IsPresentationFromModel)
                {
                    //Merge pdf
                    filename = missionDoc.CustomerProspect.FirmInstitution.PresentationFile;
                    string uploadedDoc = System.IO.Path.Combine(firmDocumentPath, filename);

                    if (System.IO.File.Exists(uploadedDoc))
                    {
                        Upsilab.Business.Configuration.FirmInstitutionPdfGeneration.GeneratePresentationByMerge(missionDoc.CustomerProspect.FirmInstitution, uploadedDoc, destBSFilePath, false, out pageCount);
                    }
                    else
                    {
                        error = _languageData.GetContent("pdf_presentation_etab_n_existe_pas_ou");
                    }

                }
                else
                {
                    //From upsideo model => generate it
                    Upsilab.Business.Configuration.FirmInstitutionPdfGeneration.GeneratePresentation(missionDoc.CustomerProspect.FirmInstitution, destBSFilePath, false);
                }

                if (!System.IO.File.Exists(destBSFilePath))
                {
                    error = _languageData.GetContent("pdf_presentation_etab_n_existe_pas_ou");
                }
                else
                {
                    //B- Prepare object to send to signature
                    SignatureParameter signatureParameter = new SignatureParameter()
                    {
                        SignatureFieldLabel = DTPClient.USER_ADVISER,

                        SignaturePosition = new SignaturePosition()
                        {
                            Page = (pageCount > 0) ? pageCount : 6, //BS : 6pages
                            X = 33,
                            Y = 177
                        }
                    };

                    signatureParametersBS.Add(signatureParameter);

                    signatureParameter = new SignatureParameter()
                    {
                        SignatureFieldLabel = DTPClient.USER_CUSTOMER,

                        SignaturePosition = new SignaturePosition()
                        {
                            Page = (pageCount > 0) ? pageCount : 6, //BS : 6pages
                            X = 120,
                            Y = 177
                        }
                    };

                    signatureParametersBS.Add(signatureParameter);


                    DocumentToSign docPE = new DocumentToSign()
                    {
                        Label = _languageData.GetContent("presentation_de_l_etab"),
                        Description = _languageData.GetContent("presentation_de_l_etab"),
                        PathFilename = destBSFilePath,
                        Type = DTPClient.DocumentTypes.APPENDIX1.ToString(),
                        SignatureParameters = signatureParametersBS
                    };

                    documentsToSign.Add(docPE);
                }
            }
            #endregion

            #region 4- Fiche d'information legale FIL => DER
            //If the DER has been signed, don't include to the doc to sign
            bool hasSignedDER = !string.IsNullOrEmpty(customer.DerStatus) && customer.DerStatus == DerModel.Status.Completed.ToString();

            if (!hasSignedDER || currentUser.IsEndUser()) //Permettre au client de signer le DER si deja joint pas le CGP
            {
                if (missionDoc.AttachInformationCard)
                {
                    List<SignatureParameter> signatureParametersDER = new List<SignatureParameter>();
                    //A- PDF ?
                    pageCount = 0;
                    docType = ElectronicSafeDocumentBL.DocumentType.FIL.ToString();
                    string firmDocumentPath = string.Format(@"{0}\FirmInstitution\FI_{1}", Server.MapPath("~/uploads"), missionDoc.CustomerProspect.FirmInstitution.idFirmInstitution);
                    destFullPath = ElectronicSafeDocumentBL.BuildClientUploadDocumentPath(docType, customer);
                    filename = ElectronicSafeDocumentBL.BuildDocumentName(docType, missionDoc.idMissionDocument, false);

                    string destFILFilePath = System.IO.Path.Combine(destFullPath, filename);

                    //From firmModel or from upsideomodel
                    if (missionDoc.IsInformationCardFromModel)
                    {
                        //Merge pdf
                        filename = missionDoc.CustomerProspect.FirmInstitution.LegalInformationFile;
                        string uploadedDoc = System.IO.Path.Combine(firmDocumentPath, filename);

                        if (System.IO.File.Exists(uploadedDoc))
                        {
                            Upsilab.Business.Configuration.FirmInstitutionPdfGeneration.GenerateDERByMerge(missionDoc.CustomerProspect.FirmInstitution, uploadedDoc, destFILFilePath, false, out pageCount);
                        }
                        else
                        {
                            error = _languageData.GetContent("le_pdf_doc_entree_en_relation_n_existe_pas");
                        }

                    }
                    else
                    {
                        //From upsideo model => generate it
                        pageCount = Upsilab.Business.Configuration.FirmInstitutionPdfGeneration.GenerateDER(missionDoc.CustomerProspect.FirmInstitution, missionDoc.CustomerProspect.idCustomer, destFILFilePath, false);
                    }

                    if (!System.IO.File.Exists(destFILFilePath))
                    {
                        error = _languageData.GetContent("le_pdf_doc_entree_en_relation_n_existe_pas");
                    }
                    else
                    {
                        //B- Prepare object to send to signature
                        SignatureParameter signatureParameter = new SignatureParameter()
                        {
                            SignatureFieldLabel = DTPClient.USER_ADVISER,

                            SignaturePosition = new SignaturePosition()
                            {
                                Page = (pageCount > 0) ? pageCount : 16, //DER : 16pages
                                X = 33,
                                Y = 177
                            }
                        };

                        signatureParametersDER.Add(signatureParameter);

                        signatureParameter = new SignatureParameter()
                        {
                            SignatureFieldLabel = DTPClient.USER_CUSTOMER,

                            SignaturePosition = new SignaturePosition()
                            {
                                Page = (pageCount > 0) ? pageCount : 16, //DER : 16pages
                                X = 120,
                                Y = 177
                            }
                        };

                        signatureParametersDER.Add(signatureParameter);

                        DocumentToSign docDER = new DocumentToSign()
                        {
                            Label = _languageData.GetContent("doc_entree_en_relation"),
                            Description = _languageData.GetContent("doc_entree_en_relation"),
                            PathFilename = destFILFilePath,
                            Type = DTPClient.DocumentTypes.APPENDIX2.ToString(),
                            SignatureParameters = signatureParametersDER
                        };

                        documentsToSign.Add(docDER);
                    }
                }
            }
            #endregion

            #region 5- Documents annexes
            var lstAppendixDocs = MissionDocumentAppendixBL.GetMissionDocumentAppendixByMissionDocument(missionDoc.idMissionDocument); //order by datecreated

            docType = ElectronicSafeDocumentBL.DocumentType.AX.ToString();
            destFullPath = ElectronicSafeDocumentBL.BuildClientUploadDocumentPath(docType, customer);

            int appendixNumber = 4;
            foreach (var appendixDoc in lstAppendixDocs)
            {
                List<SignatureParameter> signatureParametersAppendixDoc = new List<SignatureParameter>();

                //A- Generate  pdf
                pageCount = 0;

                filename = ElectronicSafeDocumentBL.BuildDocumentName(docType, appendixDoc.idMissionDocumentAppendix, false);
                var destPathFilename = System.IO.Path.Combine(destFullPath, filename);

                var sourceAppendixPathFilename = System.IO.Path.Combine(System.Web.HttpContext.Current.Server.MapPath(string.Format("~{0}", appendixDoc.Filename)));
                //On PREPROD - PROD server : always create doc to extranet_user not to extranet_client
                sourceAppendixPathFilename = sourceAppendixPathFilename.Replace(@"extranet_client", @"user");

                //Merge pdf : + page de garde (1ere page) et page de signature (2e page)
                MissionDocumentPdfGenerationBL.GenerateAppendixDocByMerge(appendixDoc, sourceAppendixPathFilename, destPathFilename, false, out pageCount);

                if (!System.IO.File.Exists(destPathFilename))
                {
                    error = _languageData.GetContent("pdf_rto_n_a_pas_ete_genere_correctement"); //TODO
                }
                else
                {
                    //B- Prepare object to send to signature
                    //Advisor signature field
                    SignatureParameter signatureParameter = new SignatureParameter()
                    {
                        SignatureFieldLabel = DTPClient.USER_ADVISER,

                        SignaturePosition = new SignaturePosition()
                        {
                            Page = pageCount,
                            X = 33,
                            Y = 177
                        }
                    };

                    signatureParametersAppendixDoc.Add(signatureParameter);

                    //Customer signature field
                    signatureParameter = new SignatureParameter()
                    {
                        SignatureFieldLabel = DTPClient.USER_CUSTOMER,

                        SignaturePosition = new SignaturePosition()
                        {
                            Page = pageCount,
                            X = 120,
                            Y = 177
                        }
                    };

                    signatureParametersAppendixDoc.Add(signatureParameter);

                    //Document to sign
                    DocumentToSign appendixDocumentToSign = new DocumentToSign()
                    {
                        Label = (!string.IsNullOrEmpty(appendixDoc.Designation)) ? appendixDoc.Designation : "Document annexe",
                        Description = (!string.IsNullOrEmpty(appendixDoc.Designation)) ? appendixDoc.Designation : "Document annexe",
                        PathFilename = destPathFilename,
                        Type = string.Format("{0}{1}", DTPClient.APPENDIX.ToString(), appendixNumber),
                        SignatureParameters = signatureParametersAppendixDoc
                    };

                    documentsToSign.Add(appendixDocumentToSign);
                }

                appendixNumber++;
            }
 

            #endregion

            return documentsToSign;
            
        }