package ee.cybernetica.uxp.securityserverloadtesting.service.repository;

import ee.cybernetica.uxp.securityserverloadtesting.service.models.response.Attachment;
import ee.cybernetica.uxp.securityserverloadtesting.service.models.response.Response;
import org.springframework.stereotype.Component;

import javax.activation.DataHandler;
import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Component
public class AttachmentRepository {

    private static final Map<Integer, Response> RESPONSE_MAP = new HashMap<>();
    private byte[] attachment = new byte[0];

    @PostConstruct
    public void init() {
        Response response = new Response();
        Attachment attachment = new Attachment();

        byte[] randombytes = "whatsup".getBytes();
        DataHandler dh = new DataHandler(randombytes, "application/octet-stream");
        try {

            attachment.setContent(dh);
            response.setAttachment(attachment);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    public Response getAttachmentBySize(int size) {

        Response response = new Response();
        Attachment attachment = new Attachment();

        DataHandler datahandler = new DataHandler(getAttachment(size/2), "application/octet-stream");
        try {

            attachment.setContent(datahandler);
            response.setAttachment(attachment);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return response;
    }



    private void generateAttachment(int size) {
        byte[] bytes = new byte[size];
        for(int i = 0; i < size; ++i) {
            bytes[i] = (byte)i;
        }
        attachment = bytes;
    }

    byte[] getAttachment(int size) {
        if(size > attachment.length) {
            generateAttachment(size);
        }
        if(size < attachment.length) {
            return Arrays.copyOfRange(attachment, 0, size + 1);
        }
        return attachment;
    }
}
