/*************************************************************
 * By: Coralys Cubero Rivera
 * Date: 2019
 *************************************************************/

package uprrp.tania;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.amazonaws.auth.CognitoCachingCredentialsProvider;
import com.amazonaws.regions.Regions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

import org.json.JSONException;
import org.json.JSONObject;
import org.researchstack.backbone.StorageAccess;
import org.researchstack.backbone.answerformat.TextAnswerFormat;
import org.researchstack.backbone.model.ConsentDocument;
import org.researchstack.backbone.model.ConsentSection;
import org.researchstack.backbone.model.ConsentSignature;
import org.researchstack.backbone.result.TaskResult;
import org.researchstack.backbone.step.ConsentDocumentStep;
import org.researchstack.backbone.step.ConsentSignatureStep;
import org.researchstack.backbone.step.ConsentVisualStep;
import org.researchstack.backbone.step.FormStep;
import org.researchstack.backbone.step.QuestionStep;
import org.researchstack.backbone.task.OrderedTask;
import org.researchstack.backbone.task.Task;
import org.researchstack.backbone.ui.ViewTaskActivity;
import org.researchstack.backbone.ui.step.layout.ConsentSignatureStepLayout;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Collections;
import java.util.Objects;
import java.util.concurrent.ExecutionException;


public class GettingStarted extends AppCompatActivity {

    private static final int REQUEST_CONSENT = 0;

    public static final String VISUAL_CONSENT_IDENTIFIER = "visual_consent_identifier";
    public static final String CONSENT_DOC = "consent_doc";
    public static final String SIGNATURE_FORM_STEP = "form_step";
    public static final String NAME = "name";
    public static final String CONSENT = "consent";
    public static final String SIGNATURE = "signature";
    public String device_token;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_getting_started);

        // Get permission to write to external storage - files
        String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        requestPermissions(permissions, 1);

        //////////////////// Let's get NOTIFICATIONS //////////////////////////
        FirebaseInstanceId.getInstance().getInstanceId()
                .addOnSuccessListener(GettingStarted.this, new OnSuccessListener<InstanceIdResult>() {
                    @Override
                    public void onSuccess(InstanceIdResult instanceIdResult) {
                        device_token = instanceIdResult.getToken();
                    }
                });

        CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
                getApplicationContext(),
                "us-east-1:574094cd-0784-4e26-bd14-4fa72ae63579", // Identity pool ID
                Regions.US_EAST_1 // Region
        );

        SNSRegister snsRegister = new SNSRegister(credentialsProvider);
        snsRegister.execute();
        ////////////////////////////////////////////////////////////////

        Button createAccount = findViewById(R.id.buttonCreateAccount);
        Button loginAccount = findViewById(R.id.buttonRecoverAccount);

        createAccount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    launchConsent();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        loginAccount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Intent loginAccountIntent = new Intent(GettingStarted.this, LoginAccount.class);
                    startActivity(loginAccountIntent);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CONSENT && resultCode == RESULT_OK) {
            processConsentResult((TaskResult) data.getSerializableExtra(ViewTaskActivity.EXTRA_TASK_RESULT));
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions [], int[] grantResults) {
        if (requestCode == 1) {
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(getApplicationContext(), "Permission for writing to external storage: DENIED", Toast.LENGTH_LONG).show();
                }
        }
    }


    private void processConsentResult(TaskResult result) {
        boolean consented = (boolean) result.getStepResult(CONSENT_DOC).getResult();

        if (consented) {
            try {
                StorageAccess.getInstance().getAppDatabase().saveTaskResult(result);

                TaskResult taskResult = StorageAccess.getInstance()
                        .getAppDatabase()
                        .loadLatestTaskResult(CONSENT);

                String signatureBase64 = (String) taskResult.getStepResult(SIGNATURE)
                        .getResultForIdentifier(ConsentSignatureStepLayout.KEY_SIGNATURE);

                String signatureDate = (String) result.getStepResult(SIGNATURE)
                        .getResultForIdentifier(ConsentSignatureStepLayout.KEY_SIGNATURE_DATE);

                byte[] signatureBytes = Base64.decode(signatureBase64, Base64.DEFAULT);

                String consentFormBase64 = createPdf(signatureBytes, signatureDate);


                JSONObject signature = new JSONObject();
                try {
                    signature.put("signaturePDFBase64", consentFormBase64);
                    signature.put("signatureDate", signatureDate);
                    signature.put("token", FirebaseInstanceId.getInstance().getToken());

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                Log.d("CONSENT JSON", signature.toString());
                SendConsentForm sendConsentForm = new SendConsentForm();
                sendConsentForm.execute(signature.toString());

                SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
                SharedPreferences.Editor editor = prefs.edit();
                editor.putString("consentSignature", signatureBase64);
                editor.putString("consentDate", signatureDate);
                editor.apply();

                Intent registration = new Intent(this, RegisterActivity.class);
                startActivity(registration);
            } catch (Exception e) {
                Log.e("CONSENT ERROR", e.getMessage());
            }
        }
    }


    private void launchConsent() {
        ConsentDocument document = new ConsentDocument();
        document.setTitle("TANIA Consent");
        document.setSignaturePageTitle(R.string.rsb_consent);

        // Create consent visual sections
        ConsentSection section1 = new ConsentSection(ConsentSection.Type.Overview);
        section1.setTitle("Welcome");
        section1.setSummary("You have been invited to participate in this study whose objectives are" +
                " (1) to develop and demonstrate the utility of a mobile application (TANIA) " +
                "to collect perception data of students participating in research experiences " +
                "and (2) to use TANIA to determine the sources of self-efficacy that lead to " +
                "career exploration and decision-making in undergraduate students.");

        section1.setContent("This study is been carried out under the supervision of Dr. Juan S. Ramírez Lugo," +
                " Department of Biology and Dr. Carlos Corrada Bravo, Department of Computer Sciences" +
                " at the University of Puerto Rico, Rio Piedras Campus. You were selected to participate " +
                "in this study because you are enrolled in a course that offers a research experience " +
                "or you voluntarily participate in research with a professor affiliated to the Río Piedras" +
                " Campus. ");


        ConsentSection section2 = new ConsentSection(ConsentSection.Type.TimeCommitment);
        section2.setTitle("Time Commitment");
        section2.setSummary("In the study you will be asked to answer a questionnaire, about your perception of self-efficacy" +
                " in research, scientific identity and decision-making about your professional career at the beginning" +
                " and end of your research experience. It will take you between 10-20 minutes to answer this questionnaire.");
        section2.setContent("You are also expected to respond to short questionnaires between 1-3 times per week while you are participating" +
                " in the research. You will receive notifications at random times during your research experience and answer " +
                "questions adapted from survey instruments that have been previously validated. It will take you between " +
                "1-3 minutes to answer these questionnaires. It is expected that 25 students will participate in this phase " +
                "of the study.");

        ConsentSection section3 = new ConsentSection(ConsentSection.Type.DataGathering);
        section3.setTitle("Data Gathering");
        section3.setSummary("While answering the questions, you may feel uncomfortable because the questions " +
                "are about your general opinion about science and research and your career. If you feel " +
                "uncomfortable with the questions, you can stop and choose not to answer the question.");

        section3.setContent("In addition, when you download the application, it will occupy space in the memory " +
                "of your mobile device and also consume your data plan in the transmission of information when you " +
                "answer the questionnaires. It is estimated that the application will have a size of 40 Mb " +
                "(As reference the WhatsApp application is 88.9 Mb). Although at the moment we cannot say exactly " +
                "how much memory or data you will consume, we understand that both will be minimal. The risks of this" +
                " study are minimal. ");

        ConsentSection section4 = new ConsentSection(ConsentSection.Type.Privacy);
        section4.setTitle("Privacy");
        section4.setSummary("Your identity will be protected throughout the study. Your identifiable information " +
                "will be handled confidentially and when presenting the results of the investigation you will not " +
                "be identified.");

        section4.setContent("The information you issue through the application will be through access credentials " +
                "(username and password) that only you will know. These access credentials will be encrypted and any " +
                "subsequent association between you and your data will be made by reference to the encrypted " +
                "information, not your personal identity. The data collected through the questionnaires will " +
                "be stored digitally on a secure hard drive in the researcher's office. These data will also be stored " +
                "virtually in the cloud, with access limited only to researchers.");

        ConsentSection section5 = new ConsentSection(ConsentSection.Type.DataUse);
        section5.setTitle("Use of Data");
        section5.setSummary("The data obtained will be used to improve academic offerings and research experiences. " +
                "The results of this study may be part of a scientific publication on science education strategies and " +
                "will serve as a basis to improve the teaching curriculum. ");
        section5.setContent("It may be used to develop proposals for obtaining external funds for research. The officials " +
                "of the Rio Piedras Campus of the University of Puerto Rico and / or federal agencies responsible for ensuring " +
                "the integrity of the research may require the researcher to prove the data obtained in this study, including " +
                "this informed consent.\n" + "\n" + "The information handled by your device can be intervened or revised by " +
                "third parties. These people can be people with legitimate or illegitimate access to the device and its content " +
                "such as a family member, employer, hackers, intruders, etc. In addition, the device that you use may keep track " +
                "of the information you access or send over the Internet.\n");

        // ...add more sections as needed, then create a visual consent step
        ConsentVisualStep visualStep = new ConsentVisualStep(VISUAL_CONSENT_IDENTIFIER);
        visualStep.setStepTitle(R.string.rsb_consent);
        visualStep.setSection(section1);
        visualStep.setNextButtonString("Next");


        ConsentVisualStep visualStep2 = new ConsentVisualStep("visual_step_2");
        visualStep2.setStepTitle(R.string.rsb_consent);
        visualStep2.setSection(section2);
        visualStep2.setNextButtonString("Next");


        ConsentVisualStep visualStep3 = new ConsentVisualStep("visual_step_3");
        visualStep3.setStepTitle(R.string.rsb_consent);
        visualStep3.setSection(section3);
        visualStep3.setNextButtonString("Next");


        ConsentVisualStep visualStep4 = new ConsentVisualStep("visual_step_4");
        visualStep4.setStepTitle(R.string.rsb_consent);
        visualStep4.setSection(section4);
        visualStep4.setNextButtonString("Next");


        ConsentVisualStep visualStep5 = new ConsentVisualStep("visual_step_5");
        visualStep5.setStepTitle(R.string.rsb_consent);
        visualStep5.setSection(section5);
        visualStep5.setNextButtonString("Next");


        // Create consent signature object and set what info is required
        ConsentSignature signature = new ConsentSignature();
        signature.setRequiresName(true);
        signature.setRequiresSignatureImage(true);

        // Create our HTML to show the user and have them accept or decline.
        StringBuilder docBuilder = new StringBuilder(
                "</br><div style=\"padding: 10px 10px 10px 10px;\" class='header'>");
        String title = getString(R.string.rsb_consent_review_title);
        docBuilder.append(String.format(
                "<h1 style=\"text-align: center; font-family:sans-serif-light;\">%1$s</h1>",
                title));
        String detail = getString(R.string.rsb_consent_review_instruction);
        docBuilder.append(String.format("<p style=\"text-align: center\">%1$s</p>", detail));
        docBuilder.append("</div></br>");
        docBuilder.append("<div> <h2> Welcome </h2>\n" +
                "<p align='justify'> You have been invited to participate in this study whose objectives are (1) " +
                "to develop and demonstrate the utility of a mobile application (TANIA) to collect " +
                "perception data of students participating in research experiences and (2) to use " +
                "TANIA to determine the sources of self-efficacy that lead to career exploration " +
                "and decision-making in undergraduate students. This study is been carried out " +
                "under the supervision of Dr. Juan S. Ramirez Lugo, Department of Biology and " +
                "Dr. Carlos Corrada Bravo, Department of Computer Sciences at the University of " +
                "Puerto Rico, Rio Piedras Campus. You were selected to participate in this study " +
                "because you are enrolled in a course that offers a research experience or you " +
                "voluntarily participate in research with a professor affiliated to the " +
                "Rio Piedras Campus. </p> " +
                "\n" +
                "<h2> Time Commitment </h2> " +
                "<p align='justify'> In the study you will be asked to answer a questionnaire, about your " +
                "perception of self-efficacy in research, scientific identity and decision-making " +
                "about your professional career at the beginning and end of your research experience. " +
                "It will take you between 10-20 minutes to answer this questionnaire. You are " +
                "also expected to respond to short questionnaires between 1-3 times per week " +
                "while you are participating in the research. You will receive notifications at " +
                "random times during your research experience and answer questions adapted from " +
                "survey instruments that have been previously validated. It will take you between " +
                "1-3 minutes to answer these questionnaires. It is expected that 25 students will " +
                "participate in this phase of the study.</p> " +
                "\n" +
                "<h2> Data Gathering </h2> " +
                "<p align='justify'> While answering the questions, you may feel uncomfortable because " +
                "the questions are about your general opinion about science and research and your career. " +
                "If you feel uncomfortable with the questions, you can stop and choose not to answer the question. " +
                "When you download the application, it will occupy space in the memory of your mobile device and " +
                "also consume your data plan in the transmission of information when you answer the questionnaires. " +
                "It is estimated that the application will have a size of 40 Mb (As reference the WhatsApp " +
                "application is 88.9 Mb). Although at the moment we cannot say exactly how much memory or " +
                "data you will consume, we understand that both will be minimal. The risks of this study " +
                "are minimal. </p> " +
                "\n" +
                "<h2> Privacy </h2> " +
                "<p align='justify'> Your identity will be protected throughout the study. Your identifiable " +
                "information will be handled confidentially and when presenting the results of " +
                "the investigation you will not be identified. The information you issue through " +
                "the application will be through access credentials (username and password) that " +
                "only you will know. These access credentials will be encrypted and any subsequent " +
                "association between you and your data will be made by reference to the encrypted " +
                "information, not your personal identity. The data collected through the " +
                "questionnaires will be stored digitally on a secure hard drive in the researcher's " +
                "office. These data will also be stored virtually in the cloud, with access limited " +
                "only to researchers. </p> " +
                "\n" +
                "<h2> Use of Data </h2> " +
                "<p align='justify'> The data obtained will be used to improve academic offerings and research " +
                "experiences. The results of this study may be part of a scientific publication " +
                "on science education strategies and will serve as a basis to improve the teaching " +
                "curriculum. It may be used to develop proposals for obtaining external funds for " +
                "research. The officials of the Rio Piedras Campus of the University of Puerto Rico " +
                "and / or federal agencies responsible for ensuring the integrity of the research " +
                "may require the researcher to prove the data obtained in this study, including " +
                "this informed consent. </p> " +
                "\n" +
                "<h2> General </h2> " +
                "<p align ='justify'> If you decide to participate in this study, understand that your participation " +
                "is completely voluntary and that you have the right to abstain from participating or even withdraw at " +
                "any time of the study without incurring in any penalty. In the application you will find the instructions " +
                "to withdraw from the study and stop receiving notifications if you wish. You also have the right not to " +
                "answer any question if you wish. Your participation in this study will not affect in any way your academic " +
                "evaluation in the courses in which you are carrying out this research. Finally, you have the right to " +
                "receive a copy of this document.\n" +
                "\n" + "If you have any questions or would like more information about this study, please contact " +
                "Prof. Ramirez Lugo at 787-764-0000 Ext. 88068, at 787-918-5330 or by email at juan.ramirez3@upr.edu " +
                "at any moment. If you have any questions about your rights as a participant or claim or complaint related " +
                "to your participation in this study, you may contact the Compliance Officer of the R’o Piedras Campus of " +
                "the University of Puerto Rico, at telephone 764-0000, extension 86773 or cipshi. degi@upr.edu.\n" +
                "\n" +
                "Your signature on this document means that you have decided to participate voluntarily, that the information " +
                "presented on this Consent Sheet has been discussed and that you have received a copy of this document. " +
                "This printed sheet will be stored under lock and key for a period of 5 years after completion of the " +
                "investigation and will then be shredded and discarded.</div>");

        // Create the Consent doc step, pass in our HTML doc
        ConsentDocumentStep documentStep = new ConsentDocumentStep(CONSENT_DOC);
        documentStep.setConsentHTML(docBuilder.toString());
        documentStep.setConfirmMessage(getString(R.string.rsb_consent_review_reason));

        // Create Consent form step, to get users first & last name
//        FormStep formStep = new FormStep(SIGNATURE_FORM_STEP,
//                "Form Title",
//                "Form step description");
//        formStep.setStepTitle(R.string.rsb_consent);
//
//        TextAnswerFormat format = new TextAnswerFormat();
//        format.setIsMultipleLines(false);
//
//        QuestionStep fullName = new QuestionStep(NAME, "Full name", format);
//        formStep.setFormSteps(Collections.singletonList(fullName));

        // Create Consent signature step, user can sign their name
        ConsentSignatureStep signatureStep = new ConsentSignatureStep(SIGNATURE);
        signatureStep.setStepTitle(R.string.rsb_consent);
        signatureStep.setTitle(getString(R.string.rsb_consent_signature_title));
        signatureStep.setText(getString(R.string.rsb_consent_signature_instruction));
        signatureStep.setSignatureDateFormat(signature.getSignatureDateFormatString());
        signatureStep.setOptional(false);
        signatureStep.setStepLayoutClass(ConsentSignatureStepLayout.class);

        // Finally, create and present a task including these steps.
        Task consentTask = new OrderedTask(CONSENT,
                visualStep,
                visualStep2,
                visualStep3,
                visualStep4,
                visualStep5,
                documentStep,
//                formStep,
                signatureStep);

        document.addSignature(signature);
        document.getHtmlReviewContent();

        // Launch using the ViewTaskActivity and make sure to listen for the activity result
        Intent intent = ViewTaskActivity.newIntent(this, consentTask);
        startActivityForResult(intent, REQUEST_CONSENT);

    }


    private String createPdf(byte[] signatureBytes, String consentDate) {

        Document document = new Document();
        String consentBase64 = null;
        try {
            String directory_path = Environment.getExternalStorageDirectory().getPath() + "/consent-tania-app.pdf";

            PdfWriter.getInstance(document, new FileOutputStream(directory_path));
            document.open();

            Font titleFont = new Font(Font.FontFamily.HELVETICA, 20, Font.BOLD, BaseColor.BLACK);
            Chunk titleChunk = new Chunk("Consent form:\nTANIA", titleFont);
            Paragraph title = new Paragraph(titleChunk);
            title.setAlignment(Element.ALIGN_CENTER);
            document.add(title);

            Paragraph newLine = new Paragraph("\n");
            document.add(newLine);

            String consentIntro = "You have been invited to participate in this study whose objectives are (1) " +
                    "to develop and demonstrate the utility of a mobile application (TANIA) to collect " +
                    "perception data of students participating in research experiences and (2) to use " +
                    "TANIA to determine the sources of self-efficacy that lead to career exploration " +
                    "and decision-making in undergraduate students. This study is been carried out " +
                    "under the supervision of Dr. Juan S. Ramirez Lugo, Department of Biology and " +
                    "Dr. Carlos Corrada Bravo, Department of Computer Sciences at the University of " +
                    "Puerto Rico, Rio Piedras Campus. You were selected to participate in this study " +
                    "because you are enrolled in a course that offers a research experience or you " +
                    "voluntarily participate in research with a professor affiliated to the " +
                    "Rio Piedras Campus. \n\n";
            Paragraph paragraph1 = new Paragraph(consentIntro);
            paragraph1.setAlignment(Element.ALIGN_JUSTIFIED);
            document.add(paragraph1);


            Font subTitlesFont = new Font(Font.FontFamily.HELVETICA, 14, Font.BOLD, BaseColor.BLACK);
            Chunk subtitle1 = new Chunk("Time Commitment", subTitlesFont);
            Paragraph timeCommitmentTitle = new Paragraph(subtitle1);
            document.add(timeCommitmentTitle);

            String consentTimeCommitment = "In the study you will be asked to answer a questionnaire, about your " +
                    "perception of self-efficacy in research, scientific identity and decision-making " +
                    "about your professional career at the beginning and end of your research experience. " +
                    "It will take you between 10-20 minutes to answer this questionnaire. You are " +
                    "also expected to respond to short questionnaires between 1-3 times per week " +
                    "while you are participating in the research. You will receive notifications at " +
                    "random times during your research experience and answer questions adapted from " +
                    "survey instruments that have been previously validated. It will take you between " +
                    "1-3 minutes to answer these questionnaires. It is expected that 25 students will " +
                    "participate in this phase of the study.\n ";
            Paragraph paragraph2 = new Paragraph(consentTimeCommitment);
            paragraph2.setAlignment(Element.ALIGN_JUSTIFIED);
            document.add(paragraph2);

            Chunk subtitle2 = new Chunk("Data Gathering", subTitlesFont);
            Paragraph dataGatheringTitle = new Paragraph(subtitle2);
            document.add(dataGatheringTitle);

            String consentDataGathering = "While answering the questions, you may feel uncomfortable because " +
                    "the questions are about your general opinion about science and research and your career. " +
                    "If you feel uncomfortable with the questions, you can stop and choose not to answer the question. " +
                    "When you download the application, it will occupy space in the memory of your mobile device and " +
                    "also consume your data plan in the transmission of information when you answer the questionnaires. " +
                    "It is estimated that the application will have a size of 40 Mb (As reference the WhatsApp " +
                    "application is 88.9 Mb). Although at the moment we cannot say exactly how much memory or " +
                    "data you will consume, we understand that both will be minimal. The risks of this study " +
                    "are minimal. \n ";
            Paragraph paragraph3 = new Paragraph(consentDataGathering);
            paragraph3.setAlignment(Element.ALIGN_JUSTIFIED);
            document.add(paragraph3);


            Chunk subtitle3 = new Chunk("Privacy", subTitlesFont);
            Paragraph privacyTitle = new Paragraph(subtitle3);
            document.add(privacyTitle);

            String consentPrivacy = "Your identity will be protected throughout the study. Your identifiable " +
                    "information will be handled confidentially and when presenting the results of " +
                    "the investigation you will not be identified. The information you issue through " +
                    "the application will be through access credentials (username and password) that " +
                    "only you will know. These access credentials will be encrypted and any subsequent " +
                    "association between you and your data will be made by reference to the encrypted " +
                    "information, not your personal identity. The data collected through the " +
                    "questionnaires will be stored digitally on a secure hard drive in the researcher's " +
                    "office. These data will also be stored virtually in the cloud, with access limited " +
                    "only to researchers. \n\n";

            Paragraph paragraph4 = new Paragraph(consentPrivacy);
            paragraph4.setAlignment(Element.ALIGN_JUSTIFIED);
            document.add(paragraph4);

            Chunk subtitle4 = new Chunk("Use of Data", subTitlesFont);
            Paragraph useOfDataTitle = new Paragraph(subtitle4);
            document.add(useOfDataTitle);

            String consentUseOfData = "The data obtained will be used to improve academic offerings and research " +
                    "experiences. The results of this study may be part of a scientific publication " +
                    "on science education strategies and will serve as a basis to improve the teaching " +
                    "curriculum. It may be used to develop proposals for obtaining external funds for " +
                    "research. The officials of the Rio Piedras Campus of the University of Puerto Rico " +
                    "and / or federal agencies responsible for ensuring the integrity of the research " +
                    "may require the researcher to prove the data obtained in this study, including " +
                    "this informed consent. \n\n";

            Paragraph paragraph5 = new Paragraph(consentUseOfData);
            paragraph5.setAlignment(Element.ALIGN_JUSTIFIED);
            document.add(paragraph5);

            Chunk subtitle5 = new Chunk("General", subTitlesFont);
            Paragraph generalTitle = new Paragraph(subtitle5);
            document.add(generalTitle);

            String consentGeneral = "If you decide to participate in this study, understand that your participation " +
                    "is completely voluntary and that you have the right to abstain from participating or even withdraw at " +
                    "any time of the study without incurring in any penalty. In the application you will find the instructions " +
                    "to withdraw from the study and stop receiving notifications if you wish. You also have the right not to " +
                    "answer any question if you wish. Your participation in this study will not affect in any way your academic " +
                    "evaluation in the courses in which you are carrying out this research. Finally, you have the right to " +
                    "receive a copy of this document.\n\n";

            Paragraph paragraph6 = new Paragraph(consentGeneral);
            paragraph6.setAlignment(Element.ALIGN_JUSTIFIED);
            document.add(paragraph6);

            String consentConclusion = "If you have any questions or would like more information about this study, please contact " +
                    "Prof. Ramirez Lugo at 787-764-0000 Ext. 88068, at 787-918-5330 or by email at juan.ramirez3@upr.edu " +
                    "at any moment. If you have any questions about your rights as a participant or claim or complaint related " +
                    "to your participation in this study, you may contact the Compliance Officer of the R’o Piedras Campus of " +
                    "the University of Puerto Rico, at telephone 764-0000, extension 86773 or cipshi. degi@upr.edu.\n\n" +
                    "Your signature on this document means that you have decided to participate voluntarily, that the information " +
                    "presented on this Consent Sheet has been discussed and that you have received a copy of this document. " +
                    "This printed sheet will be stored under lock and key for a period of 5 years after completion of the " +
                    "investigation and will then be shredded and discarded. \n\n\n";

            Paragraph paragraph7 = new Paragraph(consentConclusion);
            paragraph7.setAlignment(Element.ALIGN_JUSTIFIED);
            document.add(paragraph7);

            Chunk participantSignature = new Chunk("Participant's signature:", new Font(Font.FontFamily.HELVETICA, 12, Font.BOLDITALIC, BaseColor.BLACK));
            Paragraph paragraph8 = new Paragraph(participantSignature);
            document.add(paragraph8);

            Image consentSignatureImage = Image.getInstance(signatureBytes);
            Chunk signatureImage = new Chunk(consentSignatureImage, 145, -24);
            Paragraph paragraph11 = new Paragraph(signatureImage);
            document.add(paragraph11);

            Chunk signatureDate = new Chunk("Signed on: " + consentDate, new Font(Font.FontFamily.HELVETICA, 12, Font.BOLDITALIC, BaseColor.BLACK));
            Paragraph paragraph9 = new Paragraph(signatureDate);
            document.add(paragraph9);

            document.close();

            File file = new File(Environment.getExternalStorageDirectory().getPath() + "/consent-tania-app.pdf");
            int size = (int) file.length();
            byte[] consentBytes = new byte[size];

            try {
                BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
                buf.read(consentBytes, 0, consentBytes.length);
                buf.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            consentBase64 = android.util.Base64.encodeToString(consentBytes, android.util.Base64.DEFAULT);
            return consentBase64;

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (BadElementException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }

        return consentBase64;
    }
}



