package de.kopis.timeclicker;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.logging.Logger;

import org.apache.wicket.request.resource.AbstractResource;
import org.apache.wicket.util.string.StringValue;
import org.joda.time.DateTime;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import de.kopis.timeclicker.api.TimeclickerAPI;
import de.kopis.timeclicker.exceptions.NotAuthenticatedException;
import de.kopis.timeclicker.model.TimeEntry;
import de.kopis.timeclicker.model.TimeSum;

public class ListEntriesCsvProducerResource extends AbstractResource {
    private static final Logger LOGGER = Logger.getLogger(ListEntriesChartProducerResource.class.getName());

    private static final transient TimeclickerAPI api = new TimeclickerAPI();
    private int pageSize = 31;

    @Override
    protected ResourceResponse newResourceResponse(Attributes attributes) {
        if (attributes.getParameters().get("pageSize") != null) {
            final StringValue ps = attributes.getParameters().get("pageSize");
            pageSize = ps.toInt(31);
        }

        final ResourceResponse resourceResponse = new ResourceResponse();
        resourceResponse.setContentType("application/text");
        resourceResponse.setTextEncoding("utf-8");
        resourceResponse.setFileName("list.csv");

        resourceResponse.setWriteCallback(new WriteCallback() {
            @Override
            public void writeData(Attributes attributes) throws IOException {
                final UserService userService = UserServiceFactory.getUserService();
                final User currentUser = userService.getCurrentUser();

                final OutputStream outputStream = attributes.getResponse().getOutputStream();
                final Writer writer = new OutputStreamWriter(outputStream);


                try {
                    final List<TimeEntry> entries = api.list(pageSize, currentUser);
                    // sort ascending
                    Collections.sort(entries, new Comparator<TimeEntry>() {
                        @Override
                        public int compare(TimeEntry o1, TimeEntry o2) {
                            // sort ASC by start date
                            return o1.getStart().compareTo(o2.getStart());
                        }
                    });

                    writer.write("Date,Start,Stop,Sum,Tags\n");
                    for (TimeEntry entry : entries) {
                        writer.write("\"" +
                                new DateTime(entry.getStart()).toString("YYYY-MM-dd") + "\",\"" +
                                new DateTime(entry.getStart()).toString("HH:mm:ss") + "\",\"" +
                                new DateTime(entry.getStop()).toString("HH:mm:ss") + "\"," +
                                new TimeSum(entry).getDuration() + ",\"" +
                                ((entry.getTags() != null) ? entry.getTags() : "") + "\"\n");
                    }
                } catch (NotAuthenticatedException e) {
                    LOGGER.severe("Can not load entries: " + e.getMessage());
                }

                writer.flush();
                writer.close();
            }
        });

        return resourceResponse;
    }
}

@@ -35,144 +35,266 @@
 ort 
-java.io.IOException;%0Aimport java.io.OutputStream;%0Aimport java.io.OutputStreamWriter;%0Aimport java.io.Writer;%0Aimport java.util.Collec
+com.google.appengine.api.users.User;%0Aimport com.google.appengine.api.users.UserService;%0Aimport com.google.appengine.api.users.UserServiceFactory;%0Aimport de.kopis.timeclicker.api.TimeclickerAPI;%0Aimport de.kopis.timeclicker.exceptions.NotAuthenticatedExcep
 tion
-s
 ;%0Aim
@@ -302,86 +302,154 @@
 ort 
-java.util.Comparator;%0Aimport java.util.List;%0Aimport java.util.logging.Logger;%0A
+de.kopis.timeclicker.model.TimeEntry;%0Aimport de.kopis.timeclicker.model.TimeSum;%0Aimport org.apache.wicket.request.mapper.parameter.PageParameters;
 %0Aimp
@@ -598,354 +598,229 @@
 ort 
-com.google.appengine.api.users.User;%0Aimport com.google.appengine.api.users.UserService;%0Aimport com.google.appengine.api.users.UserServiceFactory;%0Aimport de.kopis.timeclicker.api.TimeclickerAPI;%0Aimport de.kopis.timeclicker.exceptions.NotAuthenticatedException;%0Aimport de.kopis.timeclicker.model.TimeEntry;%0Aimport de.kopis.timeclicker.model.TimeSum
+java.io.IOException;%0Aimport java.io.OutputStream;%0Aimport java.io.OutputStreamWriter;%0Aimport java.io.Writer;%0Aimport java.util.Collections;%0Aimport java.util.Comparator;%0Aimport java.util.List;%0Aimport java.util.logging.Logger
 ;%0A%0Ap
@@ -1211,38 +1211,114 @@
     
-if (attributes.getParameters()
+final PageParameters parameters = attributes.getParameters();%0A        if (parameters != null && parameters
 .get
@@ -1372,39 +1372,25 @@
 gValue ps = 
-attributes.getP
+p
 arameters().
@@ -1386,18 +1386,16 @@
 rameters
-()
 .get(%22pa

FIX NullPointer when downloading CSV