/**
 * 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.group.Group;
import org.apache.activeblaze.group.Member;
import org.apache.activeblaze.wire.Election;
import org.apache.activeblaze.wire.MemberImpl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Implementation of Group State
 */
public class ClusterGroup extends Group {
    static final Log LOG = LogFactory.getLog(ClusterGroup.class);
    final BlazeClusterGroupChannelImpl channel;
    private final BlazeClusterGroupConfiguration configuration;
    private ThreadPoolExecutor electionExecutor;
    private MemberImpl master;
    private List<MasterChangedListener> listeners = new CopyOnWriteArrayList<MasterChangedListener>();
    final AtomicBoolean electionFinished = new AtomicBoolean(false);

    /**
     * Constructor
     */
    protected ClusterGroup(BlazeClusterGroupChannelImpl channel) {
        super(channel);
        this.channel = channel;
        this.master = this.channel.getLocalMember();
        this.configuration = channel.getConfiguration();
    }

    /**
     * @see org.apache.activeblaze.Service#start()
     */
    public void doStart() throws Exception {
        super.doStart();
        this.electionExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {
            public Thread newThread(Runnable runnable) {
                Thread thread = new Thread(runnable, "Election{" + ClusterGroup.this.channel.getId() + "}");
                thread.setDaemon(true);
                return thread;
            }
        });
        election(null, true);
    }

    /**
     * @see org.apache.activeblaze.Service#stop()
     */
    public void doStop() throws Exception {
        super.doStop();
        if (this.electionExecutor != null) {
            List<Runnable> list = new ArrayList<Runnable>(this.electionExecutor.getQueue());
            for (Runnable r : list) {
                ElectionService es = (ElectionService) r;
                if (es != null) {
                    es.stop();
                    this.electionExecutor.remove(es);
                }
            }
            this.electionExecutor.shutdownNow();
            synchronized (this.electionFinished) {
                this.electionFinished.notifyAll();
            }
        }
    }

    /**
     * shutDown
     *
     * @see org.apache.activeblaze.group.Group#doShutDown()
     */
    public void doShutDown() throws Exception {
        super.doShutDown();
        setMaster(null);
    }

    /**
     * @return true if there is elections have finished
     */
    public boolean isElectionFinished() {
        return this.electionFinished.get();
    }

    void setElectionFinished(boolean flag) {
        synchronized (this.electionFinished) {
            this.electionFinished.set(flag);
            this.electionFinished.notifyAll();
        }
    }

    /**
     * Process a new member
     */
    protected void processMemberStarted(MemberImpl member) throws Exception {
        if (!member.equals(getLocalMember())) {
            synchronized (this.electionFinished) {
                this.electionFinished.set(false);
            }
        }
        super.processMemberStarted(member);
        if (!member.equals(getLocalMember())) {
            election(member, true);
        }
    }

    protected void processMemberStopped(MemberImpl member) throws Exception {
        synchronized (this.electionFinished) {
            this.electionFinished.set(false);
        }
        super.processMemberStopped(member);
        election(null, false);
    }

    void scheduleElection() {
        try {
            this.electionFinished.set(false);
            broadcastHeartBeat(getLocalMember());
            election(null, true);
        } catch (Exception e) {
            if (isStarted()) {
                LOG.error("Election failed ", e);
            }
        }
    }

    void election(final Member member, final boolean memberStarted) throws Exception {
        if (isStarted() && this.electionExecutor != null && !this.electionExecutor.isShutdown()) {
            synchronized (this.electionFinished) {
                this.electionFinished.set(false);
            }
            if (this.members.size() >= getConfiguration().getMinimumGroupSize()) {
                synchronized (this.electionExecutor) {
                    // remove any queued election tasks
                    List<Runnable> list = new ArrayList<Runnable>(this.electionExecutor.getQueue());
                    for (Runnable r : list) {
                        ElectionService es = (ElectionService) r;
                        if (es != null) {
                            es.stop();
                            this.electionExecutor.remove(es);
                        }
                    }
                }
                ElectionService es = new ElectionService(this, member, memberStarted);
                es.start();
                this.electionExecutor.execute(es);
            }
        }
    }

    /**
     * @return true if the coordinator for the map
     */
    protected boolean isMasterMatch() {
        String masterId = this.master != null ? this.master.getId() : "";
        boolean result = isStarted() && this.channel.getId().equals(masterId);
        return result;
    }

    protected MemberImpl getMaster() {
        return isStarted() ? this.master : null;
    }

    protected void setMaster(MemberImpl member) {
        MemberImpl oldMaster = this.master;
        this.master = member;
        if (oldMaster == null || (this.master != null && !this.master.equals(oldMaster))) {
            fireClusterChanged(this.master);
        }
    }

    protected void addMasterChangedListener(MasterChangedListener l) {
        this.listeners.add(l);
    }

    /**
     * Remove a listener for membership changes
     */
    protected void removeMasterChangedListener(MasterChangedListener l) {
        this.listeners.remove(l);
    }

    protected void fireClusterChanged(final MemberImpl newMaster) {
        if (isStarted()) {
            for (final MasterChangedListener l : this.listeners) {
                this.listenerService.execute(new Runnable() {
                    public void run() {
                        l.masterChanged(newMaster);
                    }
                });
            }
        }
    }

    void processElectionMessage(Election msg) throws Exception {
        MemberImpl from = this.members.get(msg.getMemberId());
        if (from != null && !from.getId().equals(getLocalMember().getId())) {
            LOG.debug(getLocalMember() + " Election message " + msg.getElectionType() + " from " + from);
            if (msg.getElectionType().equals(Election.ElectionType.ELECTION)) {
                Election reply = new Election();
                reply.setElectionType(Election.ElectionType.ANSWER);
                reply.setMemberId(getLocalMember().getId());
                this.channel.sendReply(from, reply, msg.getCorrelationId());
                // election(null, false);
            } else if (msg.getElectionType().equals(Election.ElectionType.MASTER)) {
                if (isValidMaster(from)) {
                    setMaster(from);
                    setElectionFinished(true);
                } else {
                    // bully a new election - not a valid master
                    scheduleElection();
                }
            }
        }
    }

    void broadcastElectionType(Election.ElectionType type) throws Exception {
        if (isStarted()) {
            Election msg = new Election();
            msg.setMemberId(this.channel.getLocalMember().getId());
            msg.setElectionType(type);
            this.channel.broadcastManagementMessage(msg);
        }
    }

    boolean waitForElection(int timeout) throws Exception {
        long deadline = 0;
        long waitTime = timeout;
        if (timeout > 0) {
            deadline = System.currentTimeMillis() + timeout;
        }
        synchronized (this.electionFinished) {
            while (isStarted() && !this.electionFinished.get() && (timeout == 0 || waitTime > 0)) {
                try {
                    this.electionFinished.wait(waitTime);
                } catch (InterruptedException e) {
                    LOG.warn("Interrupted in waitForElection");
                    stop();
                    break;
                }
                if (timeout > 0) {
                    waitTime = (int) Math.max(deadline - System.currentTimeMillis(), 0l);
                }
            }
        }
        return !isStopped() && this.electionFinished.get();
    }

    protected boolean isValidMaster(MemberImpl newMaster) {
        boolean result = newMaster.equals(getLocalMember());
        if (!result) {
            List<MemberImpl> sorted = ClusterGroup.sortMemberList(new ArrayList<MemberImpl>(this.members.values()));
            int ourOrder = sorted.indexOf(getLocalMember());
            int masterOrder = sorted.indexOf(newMaster);
            result = masterOrder >= ourOrder;
        }
        return result;
    }

    protected static List<MemberImpl> sortMemberList(List<MemberImpl> list) {
        Collections.sort(list);
        return list;
    }

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