/*
 * Copyright (c) eHealth
 */
using System;
using ikvm.extensions;
using NUnit.Framework;
using java.io;
using java.util;
using java.lang;
using org.apache.commons.io;
using org.joda.time;
using be.ehealth.businessconnector.ehbox.api.domain;
using be.ehealth.businessconnector.ehbox.api.utils;
using be.ehealth.businessconnector.ehbox.v3.util;
using be.ehealth.technicalconnector.exception;
using be.ehealth.technicalconnector.idgenerator;
using be.ehealth.technicalconnector.utils;
using be.fgov.ehealth.ehbox.consultation.protocol.v3;
using be.fgov.ehealth.ehbox.core.v3;
using be.fgov.ehealth.technicalconnector.tests.utils;

namespace be.ehealth.businessconnector.ehboxv3.service
{
    [TestFixture]
    public class EhboxTestDataBuilder
    {
        
        /**
         * 
         */
        private static string inssUser2;
        
        private static string inssUser1;
        
        private static string inssUser3;
        
        private static string nihiiUser1;
        
        private static string professionType;
        
        private static string qualityUser1;
        
        private static string qualityUser2;
        
        private static string qualityUser3;
        
        private static string firstNameUser1;
        
        private static string lastNameUser1;
        
        static string LOREMIPSUM = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris porttitor lacus sit amet tellus iaculis, et gravida lacus elementum. Sed facilisis libero et feugiat vulputate. Vivamus vehicula tellus orci, ac tristique velit lobortis pellentesque. Etiam feugiat condimentum mi sit amet volutpat. Curabitur ut tristique dolor. Nullam in sapien eleifend, auctor quam non, rhoncus mauris. Suspendisse quis ligula fermentum, egestas lacus quis, blandit orci. Curabitur sed tellus condimentum, hendrerit felis ac, tristique est. Pellentesque sit amet posuere nibh, non gravida purus. Morbi ultrices lectus vitae leo egestas tincidunt.\n"
            + "Etiam mauris purus, egestas interdum mi ac, rhoncus lacinia purus. Ut sodales tellus in cursus mollis. Morbi commodo ipsum purus, non gravida tortor laoreet ac. Vivamus pharetra ante metus, et condimentum est porttitor a. Phasellus elementum eros eget ligula tincidunt, ac cursus dolor ornare. In vitae augue nibh. Nulla ac convallis lectus.";
        
        
        
        /**
         * private Constructor , only static methods needed.
         */
        static EhboxTestDataBuilder() {
            try {
                Properties properties = TestPropertiesLoader.getProperties(".\\be.ehealth.businessconnector.ehboxv3.test.properties");
                inssUser2 = properties.getProperty("test.user.niss.user2");
                inssUser1 = properties.getProperty("test.user.niss.user1");
                inssUser3 = properties.getProperty("test.user.niss.user3");
                nihiiUser1 = properties.getProperty("test.user.nihii.user1");
                
                qualityUser2 = properties.getProperty("test.user.quality.user2");
                qualityUser1 = properties.getProperty("test.user.quality.user1");
                qualityUser3 = properties.getProperty("test.user.quality.user3");
                
                firstNameUser1 = properties.getProperty("test.user.firstname.user1");
                lastNameUser1 = properties.getProperty("test.user.lastname.user1");
                
                
                professionType = properties.getProperty("session.professionType");
                // EHCON-463 : retrieve property for nihii number sender from session test properties + add property with quality of sender
            } catch (TechnicalConnectorException e) {
                System.Console.WriteLine("failed to load testproperties : " + e.getMessage());
            }
        }
        
        
        /**
         * @return the inssUser2
         */
        public static string getInssUser2() {
            return inssUser2;
        }
        
        
        /**
         * @return the inssUser1
         */
        public static string getInssUser1() {
            return inssUser1;
        }
        
        
        /**
         * @return the inssUser3
         */
        public static string getInssUser3() {
            return inssUser3;
        }
        
        
        /**
         * @return the nihiiUser1
         */
        public static string getNihiiUser1() {
            return nihiiUser1;
        }
        
        /**
         * @param encrypted bool use encryption or not
         * @return
         * @throws TechnicalConnectorException
         */
        public static NewsMessage buildFullExampleNewsMessage(bool encrypted, bool useFreeTextTable) {
            return buildFullExampleNewsMessage(encrypted, useFreeTextTable, null);
        }
        
        /**
         * @param encrypted bool , use encryption or not
         * @param sender the sender to use
         * @return
         * @throws TechnicalConnectorException
         */
        public static NewsMessage buildFullExampleNewsMessage(bool encrypted, bool useFreeTextTable, Addressee sender)  {
            NewsMessage newsMessage = new NewsMessage();
            fillDocumentMessage(newsMessage, encrypted, useFreeTextTable, sender);
            return newsMessage;
        }
        
        public static DocumentMessage buildFullExampleDocumentMessage(bool encrypted, bool useFreeTextTable)  {
            return buildFullExampleDocumentMessage(encrypted, useFreeTextTable, null);
        }
        
        public static DocumentMessage buildFullExampleDocumentMessage(bool encrypted, bool useFreeTextTable, Addressee sender)  {
            DocumentMessage documentMessage = new DocumentMessage();
            fillDocumentMessage(documentMessage, encrypted, useFreeTextTable, sender);
            return documentMessage;
        }
        
        /**
         * @param documentMessage
         * @param sender if filled out this sender is used
         * @throws TechnicalConnectorException
         */
        private static void fillDocumentMessage(DocumentMessage documentMessage, bool encrypted, bool useFreeTextTable, Addressee sender) {
            documentMessage.setDestinations(new java.util.ArrayList());
            // User3 is not known as nurse in accept for the moment
            documentMessage.getDestinations().add(getAdresseeUser3());
            documentMessage.getDestinations().add(getAdresseeUser2());
            documentMessage.getDestinations().add(getAdresseeUser1());
            documentMessage.getDestinations().add(getAddresseeNihiiUser1());
            documentMessage.generatePublicationId();
            documentMessage.setId(IdGeneratorFactory.getIdGenerator().generateId().Substring(0, 13));
            documentMessage.setUseReceivedReceipt(true);
            org.joda.time.DateTime now = new org.joda.time.DateTime();
            java.lang.StringBuilder senderIdBuilder = new java.lang.StringBuilder("sender:");
            if (sender != null) {
                senderIdBuilder.append(sender.getId()).append("-").append(sender.getQuality()).append("-").append(sender.getType());
            } else {
                senderIdBuilder.append(":default");
            }
            documentMessage.setDocument(generateDocumentStr("docTitle: " + senderIdBuilder.toString() + "day:" + now.getDayOfYear() + " h:" + now.getHourOfDay() + " m:" + now.getMinuteOfHour() + " s:" + now.getSecondOfMinute() + "." + now.getMillisOfSecond()));
            documentMessage.setEncrypted(encrypted);
            documentMessage.setExpirationDateTime(new org.joda.time.DateTime(989456123L)); // should be ignored
            if (useFreeTextTable) {
                documentMessage.setFreeInformationTableTitle("freeInformationTableTitle");
                documentMessage.setFreeInformationTableRows(createStringStringHashMap());
            } else {
                documentMessage.setFreeText("freeText String " + LOREMIPSUM);
            }
            documentMessage.setHasAnnex(true);
            documentMessage.setHasFreeInformations(true);
            documentMessage.setImportant(true);
            documentMessage.setMandatee(getAdresseeUser2()); // normally this should be ignored
            documentMessage.setPatientInss(inssUser2);
            documentMessage.setSender(sender);
            documentMessage.setUsePublicationReceipt(true);
            documentMessage.setUseReadReceipt(true);
            documentMessage.setUseReceivedReceipt(true);
            documentMessage.getAnnexList().add(generateDocumentStr("annex1"));
            documentMessage.getAnnexList().add(generateDocumentStr("annex2"));
            documentMessage.getCopyMailTo().add("dummy@ehealth.fgov.be");
            documentMessage.getCustomMetas().put("customMetaKey1", "customMetaValue1");
            documentMessage.getCustomMetas().put("customMetaKey2", "customMetaValue2");
        }
        
        /**
         * @return
         */
        public static Addressee getAddresseeNihiiUser1() {
            return new Addressee(nihiiUser1, QualityType.GENERAL_PRACTIONER_NIHII);
        }
        
        /**
         * @return
         */
        static Addressee getAdresseeUser3() {
            return new Addressee(inssUser3, QualityType.NURSE_SSIN);
        }
        
        /**
         * @return
         */
        public static Addressee getAdresseeUser1() {
            Addressee addressee = new Addressee(inssUser1, QualityType.GENERAL_PRACTIONER_SSIN);
            addressee.setFirstName(firstNameUser1);
            addressee.setLastName(lastNameUser1);
            return addressee;
        }
        
        /**
         * @return
         */
        public static Addressee getAdresseeAllDoctors() {
            return new Addressee("ALL", QualityType.GENERAL_PRACTIONER_NIHII);
        }
        
        /**
         * @return
         */
        public static java.util.Map createStringStringHashMap() {
            HashMap hashMap = new HashMap();
            hashMap.put("key1", "value1");
            hashMap.put("key2", "value2");
            return hashMap;
        }
        
        /**
         * @param string
         * @return
         */
        public static Document generateDocumentStr(string title) {
            Document document = new Document();
            document.setFilename("fileName " + title);
            document.setMimeType("text/xml");
            document.setTitle(title);
            string content = "documentContent " + LOREMIPSUM;
            document.setContent(content.getBytes());
            SigningValue signing = new SigningValue();
            signing.setSigningDownloadFileName("signingDownloadFileName");
            signing.setSigningType("signingType");
            signing.setTextSigningContent("msjklmfsdqjflmsdjf");
            document.setSigning(signing);
            return document;
        }
        
        /**
         * @param string
         * @return
         */
        public static Document generateDocument(string title, string mimeType) {
            Document document = new Document();
            document.setFilename("fileName " + title);
            document.setMimeType(mimeType);
            document.setTitle(title);
            string content = "documentContent " + LOREMIPSUM;
            document.setContent(content.getBytes());
            SigningValue signing = new SigningValue();
            signing.setSigningDownloadFileName("signingDownloadFileName");
            signing.setSigningType("signingType");
            signing.setTextSigningContent("msjklmfsdqjflmsdjf");
            document.setSigning(signing);
            return document;
        }
        
        /**
         * @return
         */
        public static Addressee getAdresseeUser2() {
            return new Addressee(inssUser2, QualityType.GENERAL_PRACTIONER_SSIN);
        }
        
        /**
         * @return
         */
        public static BoxIdType getInssBoxIdUser1() {
            BoxIdType boxId = new BoxIdType();
            boxId.setId(inssUser1);
            boxId.setQuality(qualityUser1);
            boxId.setType("INSS");
            return boxId;
        }
        
        /**
         * @return
         */
        public static BoxIdType getInssBoxIdUser2() {
            BoxIdType boxId = new BoxIdType();
            boxId.setId(inssUser2);
            boxId.setQuality(qualityUser2);
            boxId.setType("INSS");
            return boxId;
        }
        
        /**
         * @return
         */
        public static BoxIdType getInssBoxIdUser3() {
            BoxIdType boxId = new BoxIdType();
            boxId.setId(inssUser3);
            boxId.setQuality(qualityUser3);
            boxId.setType("INSS");
            return boxId;
        }
        
        /**
         * @return
         */
        public static BoxIdType getRizivBoxUser1() {
            BoxIdType boxId = new BoxIdType();
            boxId.setId(nihiiUser1);
            boxId.setQuality(qualityUser1);
            boxId.setType("NIHII");
            QualityType.DENTIST_NIHII.getIdentifierType();
            return boxId;
        }
        
        /**
         * @return
         */
        public static BoxIdType GetEhboxSender() {
            try {
                BoxIdType boxId = new BoxIdType();
                QualityMapper qualityMapper = QualityMapper.getMapper(professionType);
                
                boxId.setId(getIdFromSession(qualityMapper.getType()));
                // Session.getInstance().
                boxId.setQuality(qualityMapper.getQuality());
                boxId.setType(qualityMapper.getType());
                return boxId;
            } catch (java.lang.Exception e) {
                System.Console.WriteLine("failed to load testproperties : " + e.getMessage());
                throw new RuntimeException(e);
            }
        }
        
        
        /**
         * @param qualityMapper
         */
        private static string getIdFromSession(string type)  {
            if ("INSS".Equals(type)) {
                return SessionUtil.getNiss();
            } else if ("NIHII".Equals(type)) {
                return SessionUtil.getNihii();
            } else if ("NIHII11".Equals(type)) {
                return SessionUtil.getNihii11();
            } else {
                throw new java.lang.IllegalArgumentException("Type " + type + " not authorized at this level, must be in [INSS, NIHII, NIHII11]");
            }
        }
        
        /**
         * @param sizeInKb
         * @return
         */
        public static Document buildDocumentWithSize(int sizeInKb)  {
            Document generateDocument = generateDocumentStr("document with size " + sizeInKb + " kB");
            File tempFile = File.createTempFile("someLargfileForEhboxAttachment", "txt");
            tempFile.deleteOnExit();
            FileOutputStream openOutputStream = FileUtils.openOutputStream(tempFile, true);
            byte[] someBytesToUse = LOREMIPSUM.getBytes();
            int numberOftimestoAddBytes = (sizeInKb * 1024) / someBytesToUse.Length;
            for (int i = 0; i < numberOftimestoAddBytes; i++) {
                openOutputStream.write(someBytesToUse);
                if (i % 10 == 0) {
                    openOutputStream.flush();
                }
            }
            openOutputStream.flush();
            openOutputStream.close();
            
            generateDocument.setContent(FileUtils.openInputStream(tempFile));
            return generateDocument;
        }
    }
}
