package elements.messages;

import elements.exceptions.NoAuthorMessageException;
import elements.exceptions.NoUsernameMessageException;
import org.json.JSONObject;

/**
 * Created by Guillermo Serrahima on 10/8/16.
 */
public class ChannelMessage extends Message {
    private Long cid;         //chat id
    private Integer mid;      //message id
    private Integer uid;      //user id
    private String chatType;  //chat type
    private String fullName;  //author name
    private String userName;  //username
    private String chatName;  //chat name
    private String text;      //the actual message
    private String consoleLog;

    public ChannelMessage(JSONObject message) {
        super(message);

        //Check for User
        if(message.has("from")) {
            fullName = message.getJSONObject("from").getString("first_name");
            uid = message.getJSONObject("from").getInt("id");

            //Check for user last name
            if (message.getJSONObject("from").has("last_name"))
                fullName += " " + message.getJSONObject("from").getString("last_name");

            //Check for user username
            if (message.getJSONObject("from").has("username"))
                userName = message.getJSONObject("from").getString("username");
            else userName = null;
        }

        else {
            fullName = null;
            uid = null;
            userName = null;
        }

        //Get group chat name
        if (message.getJSONObject("chat").has("title"))
            chatName = message.getJSONObject("chat").getString("title");
        else chatName = null;

        if (message.has("text"))
            text = message.getString("text");
        else text = null;

        consoleLog = message.toString();
    }

    public String getChatType() {
        return chatType;
    }

    @Override
    public boolean hasAuthor() {
        return fullName != null;
    }

    @Override
    public int getUid() throws NoAuthorMessageException {
        if(!hasAuthor()) throw new NoAuthorMessageException();
        return uid;
    }

    @Override
    public String getAuthor() throws NoAuthorMessageException {
        if(!hasAuthor()) throw new NoAuthorMessageException();
        return fullName;
    }

    public String getUsername() throws NoUsernameMessageException, NoAuthorMessageException {
        if(!hasAuthor()) throw new NoAuthorMessageException();
        if(userName == null) throw new NoUsernameMessageException();
        return userName;
    }

    public String getChatName() {
        return chatName;
    }

    @Override
    public boolean isBasicGroup() {
        return false;
    }

    @Override
    public boolean isSupergroup() {
        return false;
    }

    @Override
    public boolean isChannel() {
        return true;
    }

    @Override
    public boolean isPrivate() {
        return false;
    }
}
