package com.atlassian.stash.internal.jira;

import com.atlassian.crowd.model.application.ApplicationType;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.util.Collections;
import java.util.List;

/**
 * Entity to serialize/deserialize the request/response provided by the Crowd REST end point.
 *
 * @see <a href="https://extranet.atlassian.com/display/INTEGRATION/Application+Management+REST+API#ApplicationManagementRESTAPI-ApplicationResourceforJaaCS">
 *     Application Resource for JaaCS (figure 2)</a>
 * @see <a href="http://download.oracle.com/javaee/5/api/javax/xml/bind/annotation/package-summary.html">Annotations for XML Schema</a>
 */
@XmlRootElement(name = "application")
public class CrowdApplicationEntity {

    @XmlElement
    private String name;

    @XmlElement
    @XmlJavaTypeAdapter(ApplicationTypeAdapter.class)
    private ApplicationType type;

    @XmlElement
    private String description;

    @XmlElement
    private boolean active;

    @XmlElementWrapper(name = "password")
    @XmlElement(name = "value")
    private List<String> password;

    public CrowdApplicationEntity() {
    }

    public CrowdApplicationEntity(ApplicationType type, String name, String password, String description, boolean active) {
        this.type = type;
        this.active = active;
        this.description = description;
        this.name = name;
        this.password = Collections.singletonList(password);
    }

    public String getName() {
        return name;
    }

    public String getPassword() {
        if (password == null || password.size() != 1) {
            throw new IllegalStateException("Invalid password: " + password);
        }

        return password.get(0);
    }

    private static class ApplicationTypeAdapter extends XmlAdapter<String, ApplicationType> {

        @Override
        public String marshal(ApplicationType v) throws Exception {
            return v.name();
        }

        @Override
        public ApplicationType unmarshal(String v) throws Exception {
            return ApplicationType.valueOf(v);
        }

    }

}