/**
 * 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.group;

import org.apache.activeblaze.BaseService;
import org.apache.activeblaze.Subscription;
import org.apache.activeblaze.wire.MemberImpl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.*;
import java.util.concurrent.*;

/**
 * Maintains members of a group
 */
public class Group extends BaseService {
    static final Log LOG = LogFactory.getLog(Group.class);
    final BlazeGroupChannelImpl channel;
    private final BlazeGroupConfiguration configuration;
    Timer heartBeatTimer;
    private Timer checkMemberShipTimer;
    protected Map<String, MemberImpl> members = new ConcurrentHashMap<String, MemberImpl>();
    private List<MemberChangedListener> membershipListeners = new CopyOnWriteArrayList<MemberChangedListener>();
    private final Map<Subscription, List<MemberImpl>> queueMap = new ConcurrentHashMap<Subscription, List<MemberImpl>>();
    private final Map<Subscription, List<MemberImpl>> topicMap = new ConcurrentHashMap<Subscription, List<MemberImpl>>();
    private final Object memberMutex = new Object();
    protected ExecutorService listenerService;

    /**
     * Constructor
     */
    protected Group(BlazeGroupChannelImpl channel) {
        this.channel = channel;
        this.configuration = channel.getConfiguration();
    }

    /**
     * @return the Member of the Channel
     */
    public MemberImpl getLocalMember() {
        return this.channel.getLocalMember();
    }

    void updateLocal(MemberImpl member) {
        this.members.put(member.getId(), member);
    }

    /**
     * @return the id of the local channel associated with this group
     */
    public String getId() {
        return this.channel.getId();
    }

    /**
     * @return the name of the local channel
     */
    public String getName() {
        return this.channel.getName();
    }

    /**
     * @return the configuration associated with this channel
     */
    public BlazeGroupConfiguration getConfiguration() {
        return this.configuration;
    }

    void addMemberChangedListener(MemberChangedListener l) {
        this.membershipListeners.add(l);
    }

    void removeMemberChangedListener(MemberChangedListener l) {
        this.membershipListeners.add(l);
    }

    /**
     * @return the members
     */
    Set<Member> getMembers() {
        return new HashSet<Member>(this.members.values());
    }

    /**
     * @return the members from this group
     */
    public Set<MemberImpl> getMembersImpl() {
        return new HashSet<MemberImpl>(this.members.values());
    }

    /**
     * @return the number of members in the group
     */
    public int getMembersCount() {
        return this.members.size();
    }

    /**
     * Get a member by its unique id
     */
    Member getMemberById(String id) {
        return this.members.get(id);
    }

    /**
     * Return a member of the Group with the matching name
     */
    Member getMemberByName(String name) {
        if (name != null) {
            for (Member member : this.members.values()) {
                if (member.getName().equals(name)) {
                    return member;
                }
            }
        }
        return null;
    }

    /**
     * Will wait for a member to advertise itself if not available
     *
     * @return the member or null
     */
    public Member getAndWaitForMemberByName(String name, int timeout) throws InterruptedException {
        Member result = null;
        long deadline = 0;
        long waitTime = timeout;
        if (timeout > 0) {
            deadline = System.currentTimeMillis() + timeout;
        }
        while (isStarted() && (timeout == 0 || waitTime > 0)) {
            result = getMemberByName(name);
            if (result == null) {
                synchronized (this.members) {
                    this.members.wait(timeout);
                }
                if (timeout > 0) {
                    waitTime = (int) Math.max(deadline - System.currentTimeMillis(), 0l);
                }
            } else {
                break;
            }
        }
        return result;
    }

    /**
     * @see org.apache.activeblaze.Service#init()
     */
    public void doInit() throws Exception {
        ThreadFactory threadFactory = new ThreadFactory() {
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setDaemon(true);
                return thread;
            }
        };
        this.listenerService = Executors.newCachedThreadPool(threadFactory);
        this.members.put(this.channel.getId(), this.channel.getLocalMember());
    }

    /**
     * @see org.apache.activeblaze.Service#shutDown()
     */
    public void doShutDown() throws Exception {
        this.members.clear();
        if (this.listenerService != null) {
            this.listenerService.shutdownNow();
        }
    }

    /**
     * @see org.apache.activeblaze.Service#start()
     */
    public void doStart() throws Exception {
        TimerTask heartbeat = new TimerTask() {
            public void run() {
                try {
                    broadcastHeartBeat(getLocalMember());
                } catch (Exception e) {
                    LOG.error("Failed to send heartbeat", e);
                }
            }
        };
        heartbeat.run();
        int interval = this.configuration.getHeartBeatInterval() / 4;
        this.heartBeatTimer = new Timer(true);
        this.heartBeatTimer.scheduleAtFixedRate(heartbeat, interval, interval);
        TimerTask checkMembership = new TimerTask() {
            public void run() {
                if (isStarted()) {
                    try {
                        checkMembership();
                    } catch (Exception e) {
                        LOG.error("Failed to checkMembership", e);
                    }
                }
            }
        };
        this.checkMemberShipTimer = new Timer(true);
        this.checkMemberShipTimer.scheduleAtFixedRate(checkMembership, interval, interval / 2);
    }

    /**
     * @see org.apache.activeblaze.Service#stop()
     */
    public void doStop() throws Exception {
        if (this.heartBeatTimer != null) {
            // Make sure we shutdown the timer before shutting down the down
            // stream
            // processors to avoid the timer getting errors.
            final CountDownLatch done = new CountDownLatch(1);
            this.heartBeatTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    Group.this.heartBeatTimer.cancel();
                    done.countDown();
                }
            }, 0);
            done.await();
            this.heartBeatTimer = null;
        }
        if (this.checkMemberShipTimer != null) {
            this.checkMemberShipTimer.cancel();
        }
    }

    /**
     * @return the String representation
     * @see java.lang.Object#toString()
     */
    public String toString() {
        return "Group " + getLocalMember().getName();
    }

    /**
     * Process a new member
     *
     * @return Member if a new member else null
     */
    protected final MemberImpl processMember(MemberImpl member) throws Exception {
        MemberImpl result = null;
        MemberImpl old = null;
        if (!member.getId().equals(getLocalMember().getId()) && isInOurGroup(member)) {
            member.setTimeStamp(System.currentTimeMillis());
            if ((old = this.members.put(member.getId(), member)) == null) {
                processMemberStarted(member);
                if (!member.getId().equals(this.channel.getId())) {
                    this.channel.sendManagementMessage(member.getAddress(), this.channel.getLocalMember());
                }
                result = member;
            } else {
                processMemberUpdate(old, member);
            }
        }
        return result;
    }

    private void fireMemberStarted(final Member member) {
        synchronized (this.memberMutex) {
            this.memberMutex.notifyAll();
        }
        LOG.debug(this.channel.getName() + " Member started " + member);
        for (final MemberChangedListener l : this.membershipListeners) {
            this.listenerService.execute(new Runnable() {
                public void run() {
                    l.memberStarted(member);
                }
            });
        }
    }

    private void fireMemberStopped(final Member member) {
        synchronized (this.memberMutex) {
            this.memberMutex.notifyAll();
        }
        LOG.debug(this.channel.getName() + " Member stopped " + member);
        for (final MemberChangedListener l : this.membershipListeners) {
            this.listenerService.execute(new Runnable() {
                public void run() {
                    l.memberStopped(member);
                }
            });
        }
    }

    void checkMembership() throws Exception {
        if (isStarted()) {
            long checkTime = System.currentTimeMillis() - this.configuration.getHeartBeatInterval();
            for (MemberImpl member : this.members.values()) {
                if (!member.getId().equals(getId()) && member.getTimeStamp() < checkTime) {
                    LOG.debug(getName() + " Member timestamp expired " + member);
                    this.members.remove(member.getId());
                    processMemberStopped(member);
                }
            }
        }
    }

    protected void processMemberStarted(MemberImpl member) throws Exception {
        processDestinationsForStarted(member, member.getSubscriptions());
        fireMemberStarted(member);
        synchronized (this.members) {
            this.members.notifyAll();
        }
    }

    protected void processMemberStopped(MemberImpl member) throws Exception {
        fireMemberStopped(member);
        processDestinationsForStopped(member, member.getSubscriptions());
    }

    private void processDestinationsForStarted(MemberImpl member, List<Subscription> subscriptionList) {
        if (subscriptionList == null) {
            return;
        }
        for (Subscription sub : subscriptionList) {
            Map<Subscription, List<MemberImpl>> map = null;
            if (sub.getDestination().isTopic()) {
                map = this.topicMap;
            } else {
                map = this.queueMap;
            }
            List<MemberImpl> membersList = map.get(sub);
            if (membersList == null) {
                membersList = new CopyOnWriteArrayList<MemberImpl>();
                map.put(sub, membersList);
            }
            membersList.add(member);
        }
    }

    private void processDestinationsForStopped(MemberImpl member, List<Subscription> subscriptionList) {
        if (subscriptionList == null) {
            return;
        }
        for (Subscription sub : subscriptionList) {
            Map<Subscription, List<MemberImpl>> map = null;
            if (sub.getDestination().isTopic()) {
                map = this.topicMap;
            } else {
                map = this.queueMap;
            }
            List<MemberImpl> membersList = map.get(sub);
            if (membersList != null) {
                membersList.remove(member);
                if (membersList.isEmpty()) {
                    map.remove(sub);
                }
            }
        }
    }

    protected void processMemberUpdate(MemberImpl oldMember, MemberImpl newMember) throws Exception {
        // check for deltas
        List<Subscription> oldList = oldMember.getSubscriptions();
        List<Subscription> newList = newMember.getSubscriptions();
        List<Subscription> removed = new ArrayList<Subscription>();
        for (Subscription s : oldList) {
            if (!newList.contains(s)) {
                removed.add(s);
            }
        }
        processDestinationsForStopped(oldMember, removed);
        List<Subscription> added = new ArrayList<Subscription>();
        for (Subscription s : newList) {
            if (!oldList.contains(s)) {
                added.add(s);
            }
        }
        processDestinationsForStarted(newMember, added);
    }

    /**
     * @return the queueMap
     */
    protected Map<Subscription, List<MemberImpl>> getQueueMap() {
        return this.queueMap;
    }

    /**
     * @return the topicMap
     */
    protected Map<Subscription, List<MemberImpl>> getTopicMap() {
        return this.topicMap;
    }

    protected void broadcastHeartBeat(MemberImpl local) throws Exception {
        if (isStarted()) {
            Group.this.channel.broadcastManagementMessage(local);
        }
    }

    protected boolean waitForNewMember(int timeout) throws Exception {
        int memberCount = this.members.size();
        long deadline = 0;
        long waitTime = timeout;
        if (timeout > 0) {
            deadline = System.currentTimeMillis() + timeout;
        }
        synchronized (this.memberMutex) {
            while (isStarted() && memberCount >= this.members.size() && (timeout == 0 || waitTime > 0)) {
                try {
                    this.memberMutex.wait(waitTime);
                } catch (InterruptedException e) {
                    LOG.warn("Interrupted in waitForMember");
                    stop();
                }
                if (timeout > 0) {
                    waitTime = Math.max(deadline - System.currentTimeMillis(), 0l);
                }
            }
        }
        return !isStopped() && memberCount < this.members.size();
    }

    protected boolean isInOurGroup(MemberImpl member) {
        return this.getLocalMember().isInSameGroup(member);
    }
}
