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

import org.apache.activeblaze.Subscription;
import org.apache.activeblaze.group.Member;
import org.apache.activeblaze.impl.destination.DestinationMatch;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Implementation of a Member
 */
public class MemberImpl extends Packet implements Member, Comparable<MemberImpl> {
    private boolean observer;
    private boolean lockedMaster;
    private String name;
    private long startTime;
    private long timeStamp;
    private long masterWeight;
    private long refinedWeight;
    private List<String> groups = new CopyOnWriteArrayList<String>();
    private List<Subscription> subscriptions = new CopyOnWriteArrayList<Subscription>();
    private InetSocketAddress socketAddress;

    /**
     * Constructor
     */
    MemberImpl() {
    }

    /**
     * Default constructor
     */
    public MemberImpl(String id, String name, long masterWeight, long refinedWeight, URI localURI) throws Exception {
        setId(id);
        InetAddress addr = InetAddress.getByName(localURI.getHost());
        this.socketAddress = new InetSocketAddress(addr, localURI.getPort());
        this.name = name;
        this.masterWeight = masterWeight;
        this.refinedWeight = refinedWeight;
        this.startTime = System.currentTimeMillis();
        this.timeStamp = this.startTime;
    }

    public MemberImpl clone() {
        MemberImpl result = new MemberImpl();
        copy(result);
        return result;
    }

    protected void copy(MemberImpl copy) {
        super.copy(copy);
        copy.observer = this.observer;
        copy.lockedMaster = this.lockedMaster;
        copy.name = this.name;
        copy.startTime = this.startTime;
        copy.timeStamp = this.timeStamp;
        copy.masterWeight = this.masterWeight;
        copy.refinedWeight = this.refinedWeight;
        copy.groups.addAll(this.groups);
        copy.subscriptions.addAll(this.subscriptions);
        copy.socketAddress = this.socketAddress;
    }

    public int getPacketType() {
        return PacketType.MEMBER.getNumber();
    }

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

    /**
     * Set the name
     */
    public void setName(String name) {
        this.name = name;
    }

    public void setMasterWeight(long masterWeight) {
        this.masterWeight = masterWeight;
    }

    /**
     * @return the startTime
     */
    public long getStartTime() {
        return this.startTime;
    }

    /**
     * @return the inbox destination
     */
    public String getInBoxDestination() {
        return getId();
    }

    /**
     * @return the SocketAddress for this member
     */
    public InetSocketAddress getAddress() {
        return this.socketAddress;
    }

    /**
     * @return the timeStamp
     */
    public long getTimeStamp() {
        return this.timeStamp;
    }

    /**
     * Set the timestamp
     */
    public void setTimeStamp(long value) {
        this.timeStamp = value;
    }

    /**
     * @return the masterWeight
     */
    public long getMasterWeight() {
        return this.masterWeight;
    }

    /**
     * @return the refined weight
     * @see org.apache.activeblaze.group.Member#getRefinedMasterWeight()
     */
    public long getRefinedMasterWeight() {
        return this.refinedWeight;
    }

    public String toString() {
        return getName() + "[" + getId() + "]w=" + getMasterWeight() + "," + getRefinedMasterWeight();
    }

    public int hashCode() {
        return this.getId().hashCode();
    }

    public boolean equals(Object obj) {
        boolean result = false;
        if (obj instanceof MemberImpl) {
            MemberImpl other = (MemberImpl) obj;
            result = this.getId().equals(other.getId());
        }
        return result;
    }

    /**
     * * Compares this member with the specified member for order. Returns a
     * negative integer, zero, or a positive integer as this object is less
     * than, equal to, or greater than the specified member.
     * <p/>
     *
     * @return a negative integer, zero, or a positive integer as this member is
     *         less than, equal to, or greater than the specified member.
     * @see java.lang.Comparable#compareTo(java.lang.Object)
     */
    public int compareTo(MemberImpl member) {
        long masterWeight = getMasterWeight();
        long otherMasterWeight = member.getMasterWeight();
        int result = (masterWeight < otherMasterWeight ? -1 : (masterWeight == otherMasterWeight ? 0 : 1));
        if (result == 0) {
            masterWeight = getRefinedMasterWeight();
            otherMasterWeight = member.getRefinedMasterWeight();
            result = (masterWeight < otherMasterWeight ? -1 : (masterWeight == otherMasterWeight ? 0 : 1));
        }
        if (result == 0) {
            result = getId().compareTo(member.getId());
        }
        return result;
    }

    /**
     * @param groupName
     */
    public void addToGroup(String groupName) {
        this.groups.add(groupName);
    }

    /**
     * @return List<Dtring> of groups
     * @see org.apache.activeblaze.group.Member#getGroups()
     */
    public List<String> getGroups() {
        return this.groups;
    }

    /**
     * @param groupName
     */
    public void removeFromGroup(String groupName) {
        this.groups.remove(groupName);
    }

    public void addSubscription(Subscription s) {
        this.subscriptions.add(s);
    }

    public void removeSubscription(Subscription s) {
        this.subscriptions.remove(s);
    }

    public void clearSubscriptions() {
        this.subscriptions.clear();
    }

    public List<Subscription> getSubscriptions() {
        return this.subscriptions;
    }

    public boolean isInSameGroup(MemberImpl other) {
        { // synchronized (other.data) {
            { // synchronized (this.data) {
                for (String b : this.groups) {
                    for (String o : other.groups) {
                        if (DestinationMatch.isMatch(b, o)) {
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }

    protected void preWrite() {
        super.preWrite();
        this.byteBool.writeBoolean(this.observer);
        this.byteBool.writeBoolean(this.lockedMaster);
    }

    public void write(BufferOutputStream out) throws IOException {
        super.write(out);
        out.writeString(getName());
        out.writeLong(this.startTime);
        out.writeLong(this.timeStamp);
        out.writeLong(this.masterWeight);
        out.writeLong(this.refinedWeight);
        List<String> list = new ArrayList<String>(this.groups);
        out.writeShort(list.size());
        for (String s : list) {
            out.writeString(s);
        }
        List<Subscription> list2 = new ArrayList<Subscription>(this.subscriptions);
        out.writeShort(list2.size());
        for (Subscription s : list2) {
            s.write(out);
        }
        InetAddress addr = this.socketAddress.getAddress();
        out.write(new Buffer(addr.getAddress()));
        out.writeInt(this.socketAddress.getPort());
    }

    public void read(BufferInputStream in) throws IOException {
        super.read(in);
        this.observer = this.byteBool.readBoolean();
        this.lockedMaster = this.byteBool.readBoolean();
        this.name = in.readString();
        this.startTime = in.readLong();
        this.timeStamp = in.readLong();
        this.masterWeight = in.readLong();
        this.refinedWeight = in.readLong();
        this.groups.clear();
        int size = in.readShort();
        for (int i = 0; i < size; i++) {
            this.groups.add(in.readString());
        }
        this.subscriptions.clear();
        size = in.readShort();
        for (int i = 0; i < size; i++) {
            Subscription s = new Subscription();
            s.read(in);
            this.subscriptions.add(s);
        }
        Buffer buffer = in.readBuffer();
        InetAddress addr = InetAddress.getByAddress(buffer.toByteArray());
        int port = in.readInt();
        this.socketAddress = new InetSocketAddress(addr, port);
    }
}
