/**
 * 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.BaseService;
import org.apache.activeblaze.group.Member;
import org.apache.activeblaze.util.AsyncGroupRequest;
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.List;

/**
 * Responsible for calling an election amongst the members and deciding a
 * coordinator
 */
class ElectionService extends BaseService implements Runnable {
    private static final Log LOG = LogFactory.getLog(ElectionService.class);
    private final ClusterGroup group;
    private Member member;

    ElectionService(ClusterGroup group, Member member, boolean memberStarted) {
        this.group = group;
        this.member = member;
    }

    public void run() {
        try {
            doElection();
        } catch (Exception e) {
            LOG.error("Failed to run election", e);
        }
    }

    void doElection() throws Exception {
        List<MemberImpl> members = new ArrayList<MemberImpl>(this.group.getMembersImpl());
        if ((this.member == null || (!this.member.getId().equals(this.group.getId()) || members.size() == this.group
                .getConfiguration().getMinimumGroupSize()))) {
            // call an election
            while (!callElection() && this.group.isStarted() && isStarted())
                ;
            if (this.group.isStarted() && isStarted()) {
                this.group.setMaster(selectCordinator(members));
                if (this.group.isMasterMatch()) {
                    this.group.broadcastElectionType(Election.ElectionType.MASTER);
                }
                if (!this.group.isElectionFinished() && isStarted()) {
                    // lets just wait for more members to show
                    // we could be the coordinator now - but best to check
                    try {
                        synchronized (this.group.electionFinished) {
                            this.group.electionFinished.wait(this.group.getConfiguration().getAwaitGroupTimeout());
                        }
                    } catch (InterruptedException e) {
                    }
                }
                if (!this.group.isElectionFinished() && isStarted()) {
                    int minimumGroupSize = this.group.getConfiguration().getMinimumGroupSize();
                    if (this.group.getMembersCount() >= minimumGroupSize) {
                        // we must be the coordinator
                        this.group.setMaster(this.group.getLocalMember());
                        this.group.setElectionFinished(true);
                        LOG.debug(this.group.getLocalMember() + " I am the Master ...");
                        this.group.broadcastElectionType(Election.ElectionType.MASTER);
                    } else {
                        LOG.warn(this.group.getLocalMember() + " Do not have a minimum group (" + minimumGroupSize
                                + ")  only " + this.group.getMembersCount() + " members available");
                    }
                }
            }
        }
    }

    boolean callElection() throws Exception {
        if (isStarted()) {
            List<MemberImpl> members = new ArrayList<MemberImpl>(this.group.getMembersImpl());
            List<MemberImpl> sorted = ClusterGroup.sortMemberList(members);
            AsyncGroupRequest request = new AsyncGroupRequest();
            boolean doCall = false;
            for (MemberImpl m : sorted) {
                if (this.group.channel.getId().equals(m.getId())) {
                    doCall = true;
                } else if (doCall) {
                    Election msg = new Election();
                    msg.setMemberId(this.group.getLocalMember().getId());
                    msg.setElectionType(Election.ElectionType.ELECTION);
                    this.group.channel.sendGroupRequest(request, m, msg);
                }
            }
            boolean result = request.isSuccess(this.group.getConfiguration().getAwaitGroupTimeout());
            return result;
        }
        return false;
    }

    protected MemberImpl selectCordinator(List<MemberImpl> list) throws Exception {
        List<MemberImpl> sorted = ClusterGroup.sortMemberList(list);
        MemberImpl result = sorted.isEmpty() ? this.group.getLocalMember() : sorted.get(list.size() - 1);
        return result;
    }

    /**
     * @see org.apache.activeblaze.BaseService#doInit()
     */
    @Override
    protected void doInit() throws Exception {
        // TODO Auto-generated method stub
    }

    /**
     * @see org.apache.activeblaze.BaseService#doShutDown()
     */
    @Override
    protected void doShutDown() throws Exception {
        // TODO Auto-generated method stub
    }

    /**
     * @see org.apache.activeblaze.BaseService#doStart()
     */
    @Override
    protected void doStart() throws Exception {
        // TODO Auto-generated method stub
    }

    /**
     * @see org.apache.activeblaze.BaseService#doStop()
     */
    @Override
    protected void doStop() throws Exception {
        // TODO Auto-generated method stub
    }
}
