/*
 * CheckBalance.java
 *
 * Created on 13 december 2007, 18:31
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

/*   $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.IOException;
import java.io.InputStream;
import java.util.Vector;
import javax.microedition.io.ConnectionNotFoundException;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Ticker;

public class CheckBalance extends Thread{
    
    private BetamaxSMS parent;
    private String url;
    private String user;
    private String pass;
    private Display display;
    private Form sending;
    private Ticker waitTicker;
    private String zerothUrl = "/clx/index.php?part=logoff";
    private String firstUrl = "/clx/index.php?part=plogin&username=";
    private String secondUrl = "/clx/index.php?part=menu&justloggedin=true";
    private String balanceString = "Unable to retrieve your balance at the moment, sorry!";
    private Vector mSession;
    
    /** Creates a new instance of CheckBalance */
    public CheckBalance(BetamaxSMS parent, String url, String username, String password) {
        this.parent = parent;
        this.url = url;
        user = encr(username);
        pass = encr(password);
        zerothUrl = url+zerothUrl;
        firstUrl = url+firstUrl+user+"&password="+pass;
        secondUrl = url+secondUrl;
        mSession = new Vector();
        display=Display.getDisplay(this.parent);
        System.out.println("\nBalanceThread Created!\n"+firstUrl+"\n"+secondUrl);
    }
    
    public String encr(String input){
        String output = "";
        for(int i=0;i<input.length();i++){
            char temp = input.charAt(i);
            if(temp > '/' && temp < ':'){
                temp -= 48;
                temp = (char)((temp+5)%10);
                temp += 48;
            } else if(temp > '@' && temp < '['){
                temp -= 65;
                temp = (char)((temp+13)%26);
                temp += 65;
            } else if(temp > '\'' && temp < '{'){
                temp -= 97;
                temp = (char)((temp+13)%26);
                temp += 97;
            }
            output += temp;
        }
        return output;
    }
    
    public void run(){
        htmlReq(zerothUrl);
        String logIn = htmlReq(firstUrl);
        String loggedIn = "";
        if(logIn != null && logIn.toLowerCase().indexOf("fromlogin=true")>=0){
            sending.append("Logged in!");
            loggedIn = htmlReq(secondUrl);
            loggedIn = getBalanceFromReply(loggedIn);
            if(loggedIn != null)
                balanceString = loggedIn;
        }
        sendAlert("Remaining Credit",null,"Your balance is:\n"+balanceString,Alert.FOREVER);
    }
    
    public String getBalanceFromReply(String reply){
        String balance = null;
        try{
            int balancefound = reply.indexOf("balanceid");
            if(balancefound > 0){
                reply = reply.substring(balancefound,balancefound+40);
                reply = reply.substring(0,reply.indexOf("</b>"));
                int i = 4;
                char read = reply.charAt(reply.length()-i);
                while(read > '/' && read < ':' && i < reply.length()){
                    i++;
                    read = reply.charAt(reply.length()-i);
                }
                i--;
                reply = reply.substring(reply.length()-i);
                Double temp = new Double(Double.parseDouble(reply));
                balance = ""+temp;
            }
        }catch(Exception e){
            balance = null;
            e.printStackTrace();
        }
        return balance;
    }
    
    public String htmlReq(String location){
        HttpConnection c = null;
        InputStream s = null;
        StringBuffer b = new StringBuffer();
        boolean abort=false;
        
        sending = new Form("Remaining Credit");
        sending.setTicker(getWaitTicker());
        display.setCurrent(sending);
        
        try {
            int ch,w=0;
            c = (HttpConnection)Connector.open(location);
            if(!location.equals(zerothUrl)){
                if (mSession.size() > 0){
                    for(int i=0;i<mSession.size();i++){
                        c.setRequestProperty("cookie", (String)mSession.elementAt(i));
                    }
                }else{
                    int k=0;
                    while(c.getHeaderField(k) != null){
                        if(c.getHeaderFieldKey(k).toLowerCase().equals("set-cookie")){
                            if(c.getHeaderField(k).toLowerCase().indexOf("phpsessid") >= 0){
                                String cookie = c.getHeaderField(k);
                                int semicolon = cookie.indexOf(';');
                                cookie = cookie.substring(0, semicolon);
                                mSession.addElement((c.getHeaderField(k)));
                            }
                        }
                        k++;
                    }
                }
            }
            sending.append("Contacting "+url);
            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("Checking Balance Failed",AlertType.ERROR,"Connection failed while checking balance. 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("Checking balance failed",AlertType.ERROR,m,Alert.FOREVER);
            abort=true;
        } catch (SecurityException ex) {
            sendAlert("Checking balance failed",AlertType.ERROR,"Security problem: "+ex.getMessage(),Alert.FOREVER);
            abort=true;
        } catch (IOException ex) {
            ex.printStackTrace();
            sendAlert("Checking balance failed",AlertType.ERROR,"Unknown IO error occurred while checking balance. Please report the following line.\n"+ex.toString(),Alert.FOREVER);
            abort=true;
        } finally {
            sending.append("\nDone checking balance\nClosing connection");
            try {
                if(s != null) {
                    s.close();
                }
                if(c != null) {
                    c.close();
                }
            } catch (IOException ex) {
            }
            if(abort)
                return null;
        }
        return b.toString();
    }
    
    
    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 while checking balance");
        }
        return waitTicker;
    }
    
    public void commandAction(Command command, Displayable displayable) {
        
    }
}
