/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */
package org.apache.activeblaze.cluster;

import org.apache.activeblaze.BlazeMessage;
import org.apache.activeblaze.group.BlazeGroupChannelImpl;
import org.apache.activeblaze.group.Group;
import org.apache.activeblaze.group.Member;
import org.apache.activeblaze.util.SendRequest;
import org.apache.activeblaze.wire.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.net.URI;

/**
 * A <CODE>BlazeGroupChannel</CODE> enables peer-based point to point
 * communication and maintains a coordinator (elected leader) for the group
 */
public class BlazeClusterGroupChannelImpl extends BlazeGroupChannelImpl implements BlazeClusterGroupChannel {
    private static final Log LOG = LogFactory.getLog(BlazeClusterGroupChannelImpl.class);
    private ClusterGroup clusterGroup;
    private ClusterState state;

    /**
     * Constructor
     */
    public BlazeClusterGroupChannelImpl(String name) {
        super(name);
        this.state = new ClusterState(this);
    }

    /**
     * @return the state
     * @see org.apache.activeblaze.cluster.BlazeClusterGroupChannel#getState()
     */
    public ClusterState getState() {
        return this.state;
    }

    public void doInit() throws Exception {
        super.doInit();
        this.clusterGroup.init();
        this.state.init();
    }

    public void doShutDown() throws Exception {
        super.doShutDown();
        this.clusterGroup.shutDown();
        this.state.shutDown();
    }

    public void doStart() throws Exception {
        super.doStart();
        this.clusterGroup.start();
        this.state.start();
    }

    public void doStop() throws Exception {
        super.doStop();
        this.clusterGroup.stop();
        this.state.stop();
    }

    /**
     * @see org.apache.activeblaze.cluster.BlazeClusterGroupChannel#addMasterChangedListener(org.apache.activeblaze.cluster.MasterChangedListener)
     */
    public void addMasterChangedListener(MasterChangedListener l) throws Exception {
        init();
        this.clusterGroup.addMasterChangedListener(l);
    }

    /**
     * @return Member
     * @see org.apache.activeblaze.cluster.BlazeClusterGroupChannel#getMaster()
     */
    public Member getMaster() throws Exception {
        if (this.clusterGroup != null) {
            return this.clusterGroup.getMaster();
        }
        return null;
    }

    /**
     * @return true if the Master
     * @see org.apache.activeblaze.cluster.BlazeClusterGroupChannel#isMaster()
     */
    public boolean isMaster() throws Exception {
        if (this.clusterGroup != null) {
            return this.clusterGroup.isMasterMatch();
        }
        return false;
    }

    /**
     * @param l
     * @throws Exception
     */
    public void removeMasterChangedListener(MasterChangedListener l) throws Exception {
        if (this.clusterGroup != null) {
            this.clusterGroup.removeMasterChangedListener(l);
        }
    }

    /**
     * @return
     */
    public BlazeClusterGroupConfiguration getConfiguration() {
        return (BlazeClusterGroupConfiguration) this.configuration;
    }

    /**
     * @return true if election is finished
     */
    public boolean waitForElection(int timeout) throws Exception {
        init();
        return this.clusterGroup.waitForElection(timeout);
    }

    /**
     * @return true if there is elections have finished
     */
    public boolean isElectionFinished() throws Exception {
        init();
        return this.clusterGroup.isElectionFinished();
    }

    protected void processPacket(Packet packet) throws Exception {
        if (isStarted()) {
            processRequest(packet);
            if (packet instanceof BlazeMessage) {
            } else if (packet.getPacketType() == PacketType.MEMBER.getNumber()) {
                doProcessMember((MemberImpl) packet);
            } else if (packet.getPacketType() == PacketType.ELECTION.getNumber()) {
                doProcessElection((Election) packet);
            } else if (packet.getPacketType() == PacketType.STATE.getNumber()) {
                doProcessState((StateValue) packet);
            } else {
                LOG.error("Unexpected message type: " + packet);
            }
        }
    }

    protected MemberImpl createLocal(URI uri) throws Exception {
        BlazeClusterGroupConfiguration c = getConfiguration();
        return new MemberImpl(getId(), getName(), c.getMasterWeight(), c.getRefinedMasterWeight(), uri);
    }

    public MemberImpl getLocalMember() {
        synchronized (this.localMutex) {
            MemberImpl local = super.getLocalMember();
            long oldWeight = local.getMasterWeight();
            if (oldWeight != getConfiguration().getMasterWeight()) {
                local.setMasterWeight(getConfiguration().getMasterWeight());
                // weight changed - so do an election in case the master changed
                this.clusterGroup.scheduleElection();
            }
            return local;
        }
    }

    protected Group createGroup() {
        this.clusterGroup = new ClusterGroup(this);
        return this.clusterGroup;
    }

    protected void doProcessElection(Election election) throws Exception {
        ClusterGroup group = (ClusterGroup) getGroup();
        group.processElectionMessage(election);
    }

    protected void doProcessState(StateValue state) throws Exception {
        this.state.processState(state);
    }

    /**
     * send Request
     */
    protected Packet sendRequest(MemberImpl to, Packet packet, int timeout) throws Exception {
        Packet result = null;
        if (to != null) {
            SendRequest request = new SendRequest();
            packet.setTo(to.getAddress());
            packet.setId(this.idGenerator.generateId());
            synchronized (this.messageRequests) {
                this.messageRequests.put(packet.getId(), request);
            }
            this.unicast.downStream(packet);
            result = request.get(timeout);
        }
        return result;
    }
}
