package com.github.cstroe.spendhawk.web;

import com.github.cstroe.spendhawk.entity.Account;
import com.github.cstroe.spendhawk.helper.TransactionsHelper;
import com.github.cstroe.spendhawk.util.Ex;
import com.github.cstroe.spendhawk.util.HibernateUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;

@WebServlet("/transactions/upload")
@MultipartConfig
public class TransactionsUploadServlet extends HttpServlet {

    private static final String TEMPLATE = "/template/transactions/upload.ftl";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();

            Long accountId = Long.parseLong(req.getParameter("id"));
            Account account = Account.findById(accountId)
                .orElseThrow(Ex::accountNotFound);
            req.setAttribute("messages", new LinkedList<String>());
            req.setAttribute("account", account);

            req.getRequestDispatcher(TEMPLATE).forward(req, resp);
            HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
        } catch (Exception ex) {
            HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
            throw new ServletException(ex);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Create path components to save the file
        final String fileFormat = request.getParameter("format");
        final Part filePart = request.getPart("file");
        final Long accountId = Long.parseLong(request.getParameter("id"));
        final boolean duplicateCheck = request.getParameter("duplicate_check") != null;

        try {
            HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
            InputStream filecontent = filePart.getInputStream();
            Account account = Account.findById(accountId)
                .orElseThrow(Ex::accountNotFound);

            List<String> messages = TransactionsHelper.processFile(filecontent, account, duplicateCheck, fileFormat);

            messages.add("Duplicate check: " + Boolean.toString(duplicateCheck));

            request.setAttribute("account", account);
            request.setAttribute("messages", messages);
            request.getRequestDispatcher(TEMPLATE).forward(request, response);
            HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
        } catch (Exception ex) {
            HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
            throw new ServletException(ex);
        }
    }
}

@@ -74,82 +74,293 @@
 awk.
-entity.Account;%0Aimport com.github.cstroe.spendhawk.helper.TransactionsHelp
+bean.DateBean;%0Aimport com.github.cstroe.spendhawk.bean.transaction.ChaseCSVParser;%0Aimport com.github.cstroe.spendhawk.entity.Account;%0Aimport com.github.cstroe.spendhawk.entity.CashFlow;%0Aimport com.github.cstroe.spendhawk.entity.Transaction;%0Aimport com.github.cstroe.spendhawk.entity.Us
 er;%0A
@@ -811,16 +811,44 @@
 Stream;%0A
+import java.util.ArrayList;%0A
 import j
@@ -2351,24 +2351,26 @@
 ));%0A        
+//
 final boolea
@@ -2729,196 +2729,1234 @@
     
-List%3CString%3E messages = TransactionsHelper.processFile(file
+Account incomeAccount = account.getUser().getDefaultIncomeAccount()%0A                .orElseGet(() -%3E %7B%0A                    Account ic = new Account();%0A                    ic.setName(User.DEFAULT_INCOME_ACCOUNT_NAME);%0A                    ic.setUser(account.getUser());%0A                    ic.save();%0A                    return ic;%0A                %7D);%0A%0A            Account expenseAccount = account.getUser().getDefaultExpenseAccount()%0A                .orElseGet(() -%3E %7B%0A                    Ac
 co
+u
 nt
-ent, account, duplicateCheck, fileFormat);%0A%0A            messages.add(%22Duplicate check: %22 + Boolean.toString(duplicateCheck));
+ ec = new Account();%0A                    ec.setName(User.DEFAULT_EXPENSE_ACCOUNT_NAME);%0A                    ec.setUser(account.getUser());%0A                    ec.save();%0A                    return ec;%0A                %7D);%0A%0A            if(%22chase%22.equals(fileFormat)) %7B%0A                DateBean dateBean = new DateBean();%0A                ChaseCSVParser parser = new ChaseCSVParser(dateBean);%0A                List%3CTransaction%3E transactions = parser.parse(filecontent, account, incomeAccount, expenseAccount);%0A                for(Transaction t : transactions) %7B%0A                    t.save();%0A                    for(CashFlow f : t.getCashFlows()) %7B%0A                        f.save();%0A                    %7D%0A                %7D%0A            %7D
 %0A%0A  
@@ -4052,24 +4052,39 @@
 sages%22, 
-messages
+new ArrayList%3CString%3E()
 );%0A     

Create accounts if they don't exist.