package com.atlassian.stash.internal.web.admin;

import com.atlassian.bitbucket.i18n.I18nService;
import com.atlassian.stash.internal.avatar.InternalAvatarService;
import com.atlassian.stash.internal.web.soy.StashSoyResponseBuilder;
import com.atlassian.stash.internal.web.util.ControllerSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import static org.springframework.web.bind.annotation.RequestMethod.*;

@Controller
@RequestMapping("/admin/avatars")
public class AvatarController extends ControllerSupport {
    private static final String VIEW = "bitbucket.internal.admin.avatarsettings";
    private static final String REDIRECT_URL = "redirect:/admin/avatars";

    private final InternalAvatarService avatarService;

    @Autowired
    public AvatarController(I18nService i18nService, InternalAvatarService avatarService) {
        super(i18nService);

        this.avatarService = avatarService;
    }
    
    @RequestMapping(method = GET)
    public ModelAndView view() {
        return new StashSoyResponseBuilder(VIEW)
            .put("settings", loadSettings())
            .build();
    }

    @RequestMapping(method = POST)
    public ModelAndView update(@Validated Form form, Errors errors, RedirectAttributes redirectAttributes) {
        if (errors.hasErrors()) {
            return new StashSoyResponseBuilder(VIEW)
                .put("settings", loadSettings())
                .putValidationErrors(errors)
                .build();
        } else {
            avatarService.setEnabled(form.isEnableGravatar());
            redirectAttributes.addFlashAttribute("saved", true);
            return new StashSoyResponseBuilder(REDIRECT_URL).build();
        }
    }

    private Form loadSettings() {
        return new Form(avatarService.isEnabled());
    }

    public static class Form {
        private boolean enableGravatar;

        public Form() {
        }

        public Form(boolean enableGravatar) {
            this.enableGravatar = enableGravatar;
        }

        public void setEnableGravatar(boolean enableGravatar) {
            this.enableGravatar = enableGravatar;
        }

        public boolean isEnableGravatar() {
            return enableGravatar;
        }
    }
}
