/**
 * ******************************************************************************
 *  Copyright Fujitsu.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  You may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * *****************************************************************************
 *
 *  NIFCLOUD SDK for Java
 *
 */
package com.nifty.cloud.sdk.multiloadbalancer.model.transform;

import java.util.ArrayList;
import java.util.List;

import com.nifty.cloud.sdk.multiloadbalancer.model.DescriptionMember;
import com.nifty.cloud.sdk.multiloadbalancer.model.ElasticLoadBalancerListenerDescriptions;
import com.nifty.cloud.sdk.multiloadbalancer.model.Expectation;
import com.nifty.cloud.sdk.multiloadbalancer.model.ExpectationMember;
import com.nifty.cloud.sdk.multiloadbalancer.model.HealthCheckDescribe;
import com.nifty.cloud.sdk.multiloadbalancer.model.Instance;
import com.nifty.cloud.sdk.multiloadbalancer.model.ListenerDescribe;
import com.nifty.cloud.sdk.multiloadbalancer.model.ServerMember;
import com.nifty.cloud.sdk.multiloadbalancer.model.SorryPage;
import com.nifty.cloud.sdk.multiloadbalancer.model.StickinessPolicy;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

/**
 * ElasticLoadBalancerListenerDescriptions変換クラス。<br />
 * このクラスはレスポンスXMLからElasticLoadBalancerListenerDescriptionsクラスを生成します。
 */
public class ElasticLoadBalancerListenerDescriptionsConverter implements Converter {

    private static final String ELEMENT_MEMBER = "member";
    private static final String ELEMENT_LISTENER = "Listener";
    private static final String ELEMENT_PROTOCOL = "Protocol";
    private static final String ELEMENT_ELASTIC_LOADBALANCER_PORT = "ElasticLoadBalancerPort";
    private static final String ELEMENT_INSTANCE_PORT = "InstancePort";
    private static final String ELEMENT_BALANCING_TYPE = "BalancingType";

    private static final String ELEMENT_DESCRIPTION = "Description";
    private static final String ELEMENT_SSL_CERTIFICATE_ID = "SSLCertificateId";
    private static final String ELEMENT_SESSION_STICKINESS_POLICY = "SessionStickinessPolicy";
    private static final String ELEMENT_ENABLE = "Enabled";
    private static final String ELEMENT_METHOD = "Method";
    private static final String ELEMENT_EXPIRATION_PERIOD = "ExpirationPeriod";
    private static final String ELEMENT_SORRY_PAGE = "SorryPage";
    private static final String ELEMENT_REDIRECT_URL = "RedirectUrl";
    private static final String ELEMENT_INSTANCES = "Instances";
    private static final String ELEMENT_INSTANCE_UNIQUE_ID = "InstanceUniqueId";
    private static final String ELEMENT_INSTANCE_ID = "InstanceId";
    private static final String ELEMENT_HEALTH_CHECK = "HealthCheck";

    private static final String ELEMENT_TARGET = "Target";
    private static final String ELEMENT_INTERVAL = "Interval";
    private static final String ELEMENT_TIMEOUT = "Timeout";
    private static final String ELEMENT_UNHEALTHY_THRESHOLD = "UnhealthyThreshold";
    private static final String ELEMENT_HEALTHY_THRESHOLD = "HealthyThreshold";
    private static final String ELEMENT_PATH = "Path";
    private static final String ELEMENT_EXPECTATION = "Expectation";
    private static final String ELEMENT_HTTP_CODE = "HttpCode";
    private static final String ELEMENT_INSTANCE_STATES = "InstanceStates";

    /**
     * 変換可能なクラスか判定します。
     *
     * @param type
     *            クラス
     * @return 変換可能な場合true, 変換不可能な場合false
     *
     * @see com.thoughtworks.xstream.converters.Converter#canConvert(Class)
     */
    @SuppressWarnings("rawtypes")
    @Override
    public boolean canConvert(Class type) {
        return type == ElasticLoadBalancerListenerDescriptions.class;
    }

    @Override
    public void marshal(Object source, HierarchicalStreamWriter writer,
        MarshallingContext context) {
        // 処理無し
    }

    /**
     * {@literal
     * ElasticLoadBalancerListenerDescriptionsをElasticLoadBalancerListenerDescriptionsクラスに変換します。}
     *
     * @param reader
     *            XML読込リーダ
     * @param context
     * @return {@literal ElasticLoadBalancerListenerDescriptionsオブジェクト}
     *
     * @see com.thoughtworks.xstream.converters.Converter#unmarshal(HierarchicalStreamReader,
     *      UnmarshallingContext)
     */
    @Override
    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {

        ElasticLoadBalancerListenerDescriptions descriptions =
            new ElasticLoadBalancerListenerDescriptions();

        List<DescriptionMember> memberList = new ArrayList<DescriptionMember>();

        descriptions.setMemberList(memberList);

        String name = null;

        name = reader.getNodeName();

        while (reader.hasMoreChildren()) {

            DescriptionMember member = new DescriptionMember();

            ListenerDescribe listener = new ListenerDescribe();

            member.setListenerDescribe(listener);

            reader.moveDown();

            name = reader.getNodeName();

            if (name.equals(ELEMENT_MEMBER)) {

                reader.moveDown();

                name = reader.getNodeName();

                if (name.equals(ELEMENT_LISTENER)) {

                    while (reader.hasMoreChildren()) {

                        reader.moveDown();

                        name = reader.getNodeName();

                        if (name.equals(ELEMENT_PROTOCOL)) {
                            listener.setProtocol(reader.getValue());
                        } else if (name.equals(ELEMENT_ELASTIC_LOADBALANCER_PORT)) {
                            listener
                                .setElasticLoadBalancerPort(Integer.parseInt(reader.getValue()));
                        } else if (name.equals(ELEMENT_INSTANCE_PORT)) {
                            listener.setInstancePort(Integer.parseInt(reader.getValue()));
                        } else if (name.equals(ELEMENT_BALANCING_TYPE)) {
                            listener.setBalancingType(reader.getValue());
                        } else if (name.equals(ELEMENT_DESCRIPTION)) {
                            listener.setDescription(reader.getValue());
                        } else if (name.equals(ELEMENT_SSL_CERTIFICATE_ID)) {
                            listener.setSslCertificateId(reader.getValue());
                        } else if (name.equals(ELEMENT_SESSION_STICKINESS_POLICY)) {

                            StickinessPolicy policy = new StickinessPolicy();

                            while (reader.hasMoreChildren()) {

                                reader.moveDown();

                                name = reader.getNodeName();

                                if (name.equals(ELEMENT_ENABLE)) {
                                    policy.setEnable(Boolean.parseBoolean(reader.getValue()));
                                } else if (name.equals(ELEMENT_METHOD)) {
                                    policy.setMethod(reader.getValue());
                                } else if (name.equals(ELEMENT_EXPIRATION_PERIOD)) {
                                    policy.setExpirationPeriod(Integer.parseInt(reader.getValue()));
                                }

                                reader.moveUp();

                            }

                            listener.setStickinessPolicy(policy);

                        } else if (name.equals(ELEMENT_SORRY_PAGE)) {

                            SorryPage sorryPage = new SorryPage();

                            while (reader.hasMoreChildren()) {

                                reader.moveDown();

                                name = reader.getNodeName();

                                if (name.equals(ELEMENT_ENABLE)) {
                                    sorryPage.setEnable(Boolean.parseBoolean(reader.getValue()));
                                } else if (name.equals(ELEMENT_REDIRECT_URL)) {
                                    sorryPage.setRedirectUrl(reader.getValue());
                                }

                                reader.moveUp();

                            }

                            listener.setSorryPage(sorryPage);

                        } else if (name.equals(ELEMENT_INSTANCES)) {

                            Instance instance = new Instance();

                            List<ServerMember> instanceList = new ArrayList<ServerMember>();

                            instance.setMemberList(instanceList);

                            while (reader.hasMoreChildren()) {

                                reader.moveDown();

                                name = reader.getNodeName();

                                if (name.equals(ELEMENT_MEMBER)) {

                                    ServerMember serverMember = new ServerMember();

                                    while (reader.hasMoreChildren()) {

                                        reader.moveDown();

                                        name = reader.getNodeName();

                                        if (name.equals(ELEMENT_INSTANCE_UNIQUE_ID)) {
                                            serverMember.setInstanceUniqueId(reader.getValue());
                                        } else if (name.equals(ELEMENT_INSTANCE_ID)) {
                                            serverMember.setInstanceId(reader.getValue());
                                        }

                                        reader.moveUp();

                                    }

                                    instanceList.add(serverMember);

                                }

                                reader.moveUp();
                            }

                            listener.setInstances(instance);

                        } else if (name.equals(ELEMENT_HEALTH_CHECK)) {

                            HealthCheckDescribe healthCheck = new HealthCheckDescribe();

                            while (reader.hasMoreChildren()) {

                                reader.moveDown();

                                name = reader.getNodeName();

                                if (name.equals(ELEMENT_TARGET)) {
                                    healthCheck.setTarget(reader.getValue());
                                } else if (name.equals(ELEMENT_INTERVAL)) {
                                    healthCheck.setInterval(Integer.parseInt(reader.getValue()));
                                } else if (name.equals(ELEMENT_TIMEOUT)) {
                                    healthCheck.setTimeout(Integer.parseInt(reader.getValue()));
                                } else if (name.equals(ELEMENT_UNHEALTHY_THRESHOLD)) {
                                    healthCheck
                                        .setUnhealthyThreshold(Integer.parseInt(reader.getValue()));
                                } else if (name.equals(ELEMENT_HEALTHY_THRESHOLD)) {
                                    healthCheck
                                        .setHealthyThreshold(Integer.parseInt(reader.getValue()));
                                } else if (name.equals(ELEMENT_PATH)) {
                                    healthCheck.setPath(reader.getValue());
                                } else if (name.equals(ELEMENT_EXPECTATION)) {

                                    Expectation expectation = new Expectation();

                                    List<ExpectationMember> expectationMemberList =
                                        new ArrayList<ExpectationMember>();

                                    expectation.setMemberList(expectationMemberList);

                                    ExpectationMember expectationMember = null;

                                    expectation.setMemberList(expectationMemberList);

                                    healthCheck.setExpectation(expectation);

                                    while (reader.hasMoreChildren()) {

                                        reader.moveDown();

                                        name = reader.getNodeName();

                                        if (name.equals(ELEMENT_MEMBER)) {

                                            expectationMember = new ExpectationMember();

                                            reader.moveDown();

                                            name = reader.getNodeName();

                                            if (name.equals(ELEMENT_HTTP_CODE)) {
                                                expectationMember.setHttpCode(reader.getValue());
                                            }

                                            reader.moveUp();

                                            expectationMemberList.add(expectationMember);

                                        }

                                        reader.moveUp();

                                    }

                                    healthCheck.setExpectation(expectation);

                                } else if (name.equals(ELEMENT_INSTANCE_STATES)) {

                                    Instance instance = new Instance();

                                    healthCheck.setInstance(instance);

                                    List<ServerMember> serverMemberList =
                                        new ArrayList<ServerMember>();

                                    instance.setMemberList(serverMemberList);

                                    ServerMember serverMember = null;

                                    while (reader.hasMoreChildren()) {

                                        reader.moveDown();

                                        name = reader.getNodeName();

                                        if (name.equals(ELEMENT_MEMBER)) {

                                            serverMember = new ServerMember();

                                            while (reader.hasMoreChildren()) {

                                                reader.moveDown();

                                                name = reader.getNodeName();

                                                if (name.equals(ELEMENT_INSTANCE_UNIQUE_ID)) {
                                                    serverMember
                                                        .setInstanceUniqueId(reader.getValue());
                                                } else if (name.equals(ELEMENT_INSTANCE_ID)) {
                                                    serverMember.setInstanceId(reader.getValue());
                                                }

                                                reader.moveUp();

                                            }

                                            serverMemberList.add(serverMember);

                                        }

                                        reader.moveUp();

                                    }

                                }

                                reader.moveUp();

                            }

                            listener.setHealthCheck(healthCheck);

                        }

                        reader.moveUp();

                    }

                }

                reader.moveUp();

            }

            memberList.add(member);

            reader.moveUp();

        }

        return descriptions;
    }

}
