package it.com.atlassian.stash.timezone;

import com.atlassian.bitbucket.rest.util.ResponseFactory;
import com.atlassian.bitbucket.rest.util.RestUtils;
import com.atlassian.bitbucket.timezone.TimeZoneService;
import com.atlassian.plugins.rest.common.security.AnonymousAllowed;
import com.sun.jersey.spi.resource.Singleton;
import org.codehaus.jackson.map.annotate.JsonSerialize;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.time.ZoneId;
import java.util.Optional;

import static org.apache.commons.lang3.StringUtils.stripToNull;

/**
 * Resource to get and set time zones in the browser tests.
 *
 * @since 4.6
 */
@AnonymousAllowed
@Consumes({MediaType.APPLICATION_JSON})
@Path("timezones")
@Produces({RestUtils.APPLICATION_JSON_UTF8})
@Singleton
public class TimeZoneResource {

    private final TimeZoneService service;

    public TimeZoneResource(TimeZoneService service) {
        this.service = service;
    }

    @GET
    @Path("server")
    public Response getServerTimeZone() {
        String zoneId = service.getServerTimeZone().map(ZoneId::getId).orElse(null);
        return ResponseFactory.ok()
                .entity(new RestTimeZone(zoneId))
                .build();
    }

    @GET
    @Path("user")
    public Response getUserTimeZone() {
        String zoneId = service.getUserTimeZone().map(ZoneId::getId).orElse(null);
        return ResponseFactory.ok()
                .entity(new RestTimeZone(zoneId))
                .build();
    }

    @PUT
    @Path("server")
    public Response setServerTimeZone(RestTimeZone bean) {
        service.setServerTimeZone(Optional.ofNullable(stripToNull(bean.timeZone)).map(ZoneId::of).orElse(null));
        return ResponseFactory.noContent().build();
    }

    @PUT
    @Path("user")
    public Response setUserTimeZone(RestTimeZone bean) {
        service.setUserTimeZone(Optional.ofNullable(stripToNull(bean.timeZone)).map(ZoneId::of).orElse(null));
        return ResponseFactory.noContent().build();
    }

    public static class RestTimeZone {

        @JsonSerialize
        public String timeZone;

        public RestTimeZone() {
        }

        public RestTimeZone(String timeZone) {
            this.timeZone = timeZone;
        }
    }
}
