package com.knutejohnson.pi.chat;

import java.net.*;
import java.util.*;
import java.util.regex.*;

public class Message {
    private String handle;
    private String password;
    private String dest;
    private String text;
    private InetAddress address;

    public Message(DatagramPacket packet) {
        String str = new String(packet.getData(),packet.getOffset(),
         packet.getLength());
        address = packet.getAddress();

        // split the packet string
        String[] parts = str.split("\u0000");
        // throw a hissy if format is bad
        if (parts.length < 3 || parts.length > 4)
            throw new IllegalArgumentException("BAD PACKET");

        handle = parts[0];
        password = parts[1];
        dest = parts[2];
        if (parts.length == 4)
            text = parts[3];
        else
            text = "";
     }

    public Message(String handle, String password, String dest,
     String text, InetAddress address) {
        this.handle = handle;
        this.password = password;
        this.dest = dest;
        this.text = text;
        this.address = address;
    }

    public synchronized String getHandle() {
        return handle;
    }

    public synchronized String getPassword() {
        return password;
    }

    public synchronized String getDest() {
        return dest;
    }

    public synchronized String getText() {
        return text;
    }

    public synchronized InetAddress getAddress() {
        return address;
    }

    public synchronized Message setHandle(String handle) {
        this.handle = handle;

        return this;
    }

    public synchronized Message setPassword(String password) {
        this.password = password;

        return this;
    }

    public synchronized Message setDest(String dest) {
        this.dest = dest;

        return this;
    }

    public synchronized Message setText(String text) {
        this.text = text;

        return this;
    }

    public synchronized Message setAddress(InetAddress address) {
        this.address = address;

        return this;
    }

    public DatagramPacket toPacket() {
        String str = String.format("%s\u0000%s\u0000%s\u0000%s",
         getHandle(),getPassword(),getDest(),getText());

        DatagramPacket packet =
         new DatagramPacket(str.getBytes(),str.length());
        packet.setAddress(getAddress());

        return packet;
    }

    public String toServerString() {
        return String.format("%-16s %-15s %-16s %s\n",
         getHandle(),
         getAddress() == null ? "" : getAddress().getHostAddress(),
         getDest(),
         getText());
    }

    public String toClientString() {
        return String.format("%s > %s: %s\n",getHandle(),getDest(),getText());
    }
}