package server.handlers;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import server.db.ImageAccessor;
import server.db.UserAccessor;
import server.handlers.common.BaseHanlder;
import shared.communication.common.ARecord;
import shared.communication.params.SubmitBatch_Param;
import shared.communication.responses.SubmitBatch_Res;

import java.io.IOException;
import java.io.InputStream;


public class SubmitBatchHandler  extends BaseHanlder {

    private HttpHandler handler = new HttpHandler() {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            InputStream inputStream = exchange.getRequestBody();
            String request = inputStreamToString(inputStream);

            SubmitBatch_Param submitBatchParam = SubmitBatch_Param.serialize(request);
            UserAccessor userAccessor = UserAccessor.find(submitBatchParam.getUsername());

            if(userAccessor == null) {
                writeServerErrorResponse(exchange);
                return;
            } else if (userAccessor.login(submitBatchParam.getPassword())) {
                if(userAccessor.getImageId() != submitBatchParam.getImageId()) {
                    writeServerErrorResponse(exchange);
                    return;
                }

                ImageAccessor imageAccessor = userAccessor.getImage();
                if(imageAccessor == null
                        || submitBatchParam.getRecordValues().size()
                        != imageAccessor.getProject().getRecordsPerImage()) {

                    writeServerErrorResponse(exchange);
                    return;
                        }
                for(int i = 0; i < submitBatchParam.getRecordValues().size(); i++) {
                    ARecord aRecord = submitBatchParam.getRecordValues().get(i);
                    if(imageAccessor.getProject().getFields().size() != aRecord.getValues().size()){
                        writeServerErrorResponse(exchange);
                        return;
                    }

                    imageAccessor.addRecord(aRecord.getValues(), (i + 1));
                }
                if(imageAccessor.save()) {
                    int current = userAccessor.getIndexedRecords();
                    int toAdd = imageAccessor.getProject().getRecordsPerImage();
                    userAccessor.setIndexedRecords(current + toAdd);
                    userAccessor.setImageId(0);
                    if(userAccessor.save()) {
                        SubmitBatch_Res submitBatchRes = new SubmitBatch_Res(true);
                        writeSuccessResponse(exchange, submitBatchRes.toXML());
                        return;
                    }
                }
            }

            writeServerErrorResponse(exchange);
        }
    };

    public HttpHandler getHandler() {
        return handler;
    }

}

