/*   $Id$
 *
 *   Copyright (c) 2007 Snempaa & Richie B.
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package sendSms;

import java.io.*;
import javax.microedition.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.InvalidRecordIDException;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotOpenException;

public class SendViaStream extends Thread {
    private String url, data;
    private BetamaxSMS parent;
    private Display display;
    private Form sending;
    private Ticker waitTicker;
    private int part, total;
    
    public SendViaStream(BetamaxSMS parent, String url, String data) {
        this.url=url;
        this.parent=parent;
        this.data = data;
        part = 0;
        total = 1;
        display=Display.getDisplay(this.parent);
    }
    
    public void run(){
        HttpConnection c = null;
        InputStream s = null;
        StringBuffer b = new StringBuffer();
        boolean abort=false;
        
        sending = new Form("Sending SMS");
        sending.setTicker(getWaitTicker());
        display.setCurrent(sending);
        if(data.length() > 160){
            total = (159+data.length())/160;
        }
        String partToSend = "";
        while(data.length() > 0){
            if(data.length() < 160){
                partToSend = parent.urlEncode(data);
                data = "";
            }
            else{
                partToSend = parent.urlEncode(data.substring(0,160));
                data = data.substring(160);
            }
            part++;
            try {
                int ch,w=0;
                c = (HttpConnection)Connector.open(url+partToSend);
                sending.append("Sending part "+part+" of "+total+".");
                sending.append("Contacting "+url.substring(0,url.indexOf((int)'?')));             
                s = c.openInputStream();
                sending.append("\nWaiting for response");
                while((ch = s.read()) != -1) {
                    if(w==0) {
                        sending.append("\nReading response");
                        w=1;
                    }
                    b.append((char) ch);
                }
            } catch (ConnectionNotFoundException ex) {
                sendAlert("Part "+part+" failed",AlertType.ERROR,"Connection failed while sending SMS. Check Betamax clone on settings page.\nError: "+ex.getMessage(),Alert.FOREVER);
                abort=true;
            } catch (javax.microedition.pki.CertificateException ex) {
                String m=new String("SSL certificate error.");
                byte x=ex.getReason();
                if(x==ex.ROOT_CA_EXPIRED ||
                        x==ex.UNRECOGNIZED_ISSUER ||
                        x==ex.VERIFICATION_FAILED ||
                        x==ex.UNAUTHORIZED_INTERMEDIATE_CA)
                    m=m.concat(" Please install the proper root certificate. Probably http://www.rapidssl.com/cps/rapidssl_01.cer");
                m=m.concat("\nReason code: "+x);
                sendAlert("Sending part "+part+" failed",AlertType.ERROR,m,Alert.FOREVER);
                abort=true;
            } catch (SecurityException ex) {
                sendAlert("Part "+part+" failed",AlertType.ERROR,"Security problem: "+ex.getMessage(),Alert.FOREVER);
                abort=true;
            } catch (IOException ex) {
                ex.printStackTrace();
                sendAlert("Part "+part+" failed",AlertType.ERROR,"Unknown IO error occurred while sending SMS. Please report the following line.\n"+ex.toString(),Alert.FOREVER);
                abort=true;
            } finally {
                sending.append("\nDone sending part "+part+" of "+total+".\nClosing connection");
                try {
                    if(s != null) {
                        s.close();
                    }
                    if(c != null) {
                        c.close();
                    }
                } catch (IOException ex) {
                }
                if(abort)
                    return;
            }
            if(b.toString().toLowerCase().indexOf("succes")>=0) {
                sending.append("Part "+part+" Succesfully Sent");
            } else {
                sendAlert(getResultstring(b.toString()),AlertType.ERROR,getDescription(b.toString())+" in part "+part+"/"+total+"!",Alert.FOREVER);
                return;
            }
        }
        sendAlert("Done",null,"Sending complete!",1000);
        parent.clearText();
    }
    
    public void sleep(int i) {
        try {
            Thread.sleep(i);
        } catch (InterruptedException ex) {
        }
    }
    
    public void sendAlert(String title, AlertType type, String text, int timeout) {
        Alert a = new Alert(title);
        if(type != null)
            a.setType(type);
        a.setString(text);
        a.setTimeout(timeout);
        display.setCurrent(a,parent.sms);
    }
    
    public Ticker getWaitTicker(){
        if(waitTicker == null){
            waitTicker = new Ticker("please wait");
        }
        return waitTicker;
    }
    
    public void commandAction(Command command, Displayable displayable) {
        
    }
    
    public static String getResultstring(String s) {
        int i,j;
        i=s.indexOf("<resultstring>");
        if(i<0)
            return new String("Unknown Error");
        j=s.indexOf("</resultstring>",i);
        if(j<0)
            return new String("Unknown Error");;
            return s.substring(i+14,j);
    }
    
    public static String getDescription(String s) {
        int i,j;
        i=s.indexOf("<description>");
        if(i<0)
            return stripHTMLtags(s);
        j=s.indexOf("</description>",i);
        if(j<0)
            return stripHTMLtags(s);
        return s.substring(i+13,j);
    }
    
    public static String stripHTMLtags(String s) {
        int i,j;
        String r=s.toString();
        String t=new String();
        while((i=r.indexOf((int)'<'))>=0) {
            if((j=r.indexOf((int)'>',i))<0)
                return r;
            // handle <p> and <br> tags
            if((j-i==2 && r.substring(i+1,j).toLowerCase().equals("p")) ||
                    (j-i==3 && r.substring(i+1,j).toLowerCase().equals("br")))
                t=new String("\n");
            if(++j>r.length())
                r=r.concat(" ");
            if(i>0)
                r=r.substring(0,i)+t.toString()+r.substring(j);
            else
                r=t.toString()+r.substring(j);
            t=new String();
        }
        return r;
    }
}
