package smscomposerexample;

import java.io.IOException;
import java.io.InputStream;

import javax.bluetooth.*;
import javax.microedition.io.Connector;
import javax.obex.*;
/**
 * Trieda, ktora sluzi ako server pre bluetooth spojenie
 * @author Richard Scepko
 */
public class Server {
    /**
     * Jedinecne ID servera
     */
    static final String serverUUID = "11111111111111111111111111111123";
    public RequestHandler handler;
    /**
     * Objekt triedy SMSSend pre poslanie sms
     */
    private SMSSend smsSend;

    /**
     * Konstruktor triedy
     */
    public Server(){
       this.smsSend = new SMSSend();
    }

    /**
     * Spusta server
     * @param sms SMSComposerExample pre pristup k logovaciemu textu
     * @throws IOException
     */
    public void run(SMSComposerExample sms) throws IOException {
        //viditelny
        LocalDevice.getLocalDevice().setDiscoverable(DiscoveryAgent.GIAC);

        //otvorenie spojenia na jedinecnom ID
        SessionNotifier serverConnection = (SessionNotifier) Connector.open("btgoep://localhost:"
                + serverUUID + ";name=ObexExample");

        //Prijimanie poziadavkov
        int count = 0;
        while(count < 500) {
            handler = new RequestHandler(sms);
            serverConnection.acceptAndOpen(handler);
            System.out.println("Received OBEX connection " + (++count));
        }
    }

    public RequestHandler getHandler() {
        return handler;
    }

    public void setHandler(RequestHandler handler) {
        this.handler = handler;
    }

    /**
     * Spracovava poziadavky od klienta
     */
    public class RequestHandler extends ServerRequestHandler {
        /**
         * SMSComposerExample pre pristup k logovaciemu textu
         */
        private SMSComposerExample sms;
        /**
         * Buffer pre prichodziu spravu
         */
        private StringBuffer buf;

        /**
         * Konstruktor triedy
         * @param sms SMSComposerExample pre pristup k logovaciemu textu
         */
        public RequestHandler(SMSComposerExample sms){
            super();
            this.sms = sms;
        }

        /**
         * Ak pride sprava:
         * @param op
         * @return OBEX_HTTP_OK ak vsetko prebehlo spravne alebo OBEX_HTTP_UNAVAILABLE ak nastala chyba
         */
        public int onPut(Operation op) {
            try {
                HeaderSet hs = op.getReceivedHeaders();
                String name = (String) hs.getHeader(HeaderSet.NAME);
                if (name != null) {
                    System.out.println("put name:" + name);
                }

                InputStream is = op.openInputStream();

                this.buf = new StringBuffer();
                int data;
                while ((data = is.read()) != -1) {
                    buf.append((char) data);
                }
                //prevedie spravu do Stringu
                String get = this.getBuf().toString();
                //Sprava ma tvar [cislo]~[cislo]..~sprava, potom spravu
                //vyfiltruj tak, ze najdeme posledny vyskyt specifickeho znaku '~'
                String message = get.substring(get.lastIndexOf(126)+1); //'~' = 126
                sms.getTextBox().setString("Sending message:\n" + message + "\nto:\n");
                //pokial existuju nejake cisla
                while(get.indexOf("~") != -1){
                    //odfiltruje jedno cislo
                    String number = get.substring(0, get.indexOf("~"));
                    get = get.substring(get.indexOf("~") + 1);
                    sms.getTextBox().setString(sms.getTextBox().getString() + "\n" + number.toString());
                    //posle SMS
                    smsSend.setMessage(message);
                    smsSend.setNumber(number);
                    smsSend.setSms(this.sms);
                    smsSend.sendSMS();
                }
                //ukonci spojenie
                op.close();
                return ResponseCodes.OBEX_HTTP_OK;
            } catch (IOException e) {
                e.printStackTrace();
                return ResponseCodes.OBEX_HTTP_UNAVAILABLE;
            }
        }

        public StringBuffer getBuf() {
            return buf;
        }

        public void setBuf(StringBuffer buf) {
            this.buf = buf;
        }
    }
}