package com.funambol.omadmclient.android.testclientadapter;

import com.funambol.omadmclient.android.testclientadapter.R;

import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class TestClientAdapter extends Activity implements OnClickListener {
    private final static String LOGTAG = "TestClientAdapter";
 //   private final static String dataPathPrefix = "/data/data/";
    private final static int BUFFER_SIZE = 1024;
    private final static String initPath = "appdata";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        /*** Setup listener for Buttons ***/
        View startDMSessionButton = findViewById(R.id.startdmsession_button);
        startDMSessionButton.setOnClickListener((OnClickListener) this);
        View getManagementObjectButton = findViewById(R.id.getmanagementobject_button);
        getManagementObjectButton.setOnClickListener((OnClickListener) this);
        View setManagementObjectButton = findViewById(R.id.setmanagementobject_button);
        setManagementObjectButton.setOnClickListener((OnClickListener) this);
        View getManagementTreeButton = findViewById(R.id.getmanagementtree_button);
        getManagementTreeButton.setOnClickListener((OnClickListener) this);
        View aboutButton = findViewById(R.id.about_button);
        aboutButton.setOnClickListener((OnClickListener) this);

        if (!initApplicationData())
        {
            Log.i(LOGTAG, "Could not initialize application data");
        }
        else
        {
            Log.i(LOGTAG, "Application data initialized successful");
        }
    }
    
    /*** Callback for Buttons ***/
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.startdmsession_button:
                StartDMSession();
                break;
            case R.id.getmanagementobject_button:
                break;
            case R.id.setmanagementobject_button:
                break;
            case R.id.getmanagementtree_button:
                break;
            case R.id.about_button:
                Intent i = new Intent(this, About.class);
                startActivity(i);
                break;
            default:
                break;
        }
    }

    static {

        try {
            Log.i(LOGTAG, "Load libLogger.so");
            System.loadLibrary("Logger");
        }
        catch (UnsatisfiedLinkError ule) {
            Log.i(LOGTAG, "ERROR: Could not load libLogger.so");
        }

        try {
            Log.i(LOGTAG, "Load libTestClientAdapter.so");
            System.loadLibrary("TestClientAdapter");
        }
        catch (UnsatisfiedLinkError ule) {
            Log.i(LOGTAG, "ERROR: Could not load libTestClientAdapter.so");
        }

        try {
            Log.i(LOGTAG, "Load libJNIAdapterTestClientAdapter.so");
            System.loadLibrary("JNIAdapterTestClientAdapter");
        }
        catch (UnsatisfiedLinkError ule) {
            Log.i(LOGTAG, "ERROR: Could not load libJNIAdapterTestClientAdapter.so");
        }
    }

    public static native long GetManagementObject(String objectName);
    public static native long GetManagementTree(String uri);
    public static native long GetClientProfiles();

    public static native long SetManagementObject(String objectName);
    public static native long Set(String filename);
    public static native long SetEMSK(String emsk);
    public static native long SetManufacturer(String manufacturer);
    public static native long SetModel(String model);
    public static native long SetDeviceID(String deviceID);
    public static native long SetWiMAXDiagnostics();

    public static native long CheckFirmware();
    public static native long StartDMSession();
    public static native long HandleProvision();
    public static native long HandleConfirmation();
    public static native long Subscribe();
    public static native long DRMDReadyRequest();
    public static native long HandleNetworkEntry(int hnspID, String operatorName);

    private boolean initApplicationData() {
    	final File dataDir = getApplicationContext().getFilesDir();
        AssetManager assetManager = getResources().getAssets();

        try {
            copyFiles(assetManager, null, initPath, dataDir);
        } catch (IOException e) {
            String strError = "initApplicationData(): " + e.toString();
            Log.i(LOGTAG, strError);
            return false;
        }
        return true;
    }

    private void copyFiles(AssetManager assetManager, final String parentPath, final String filename, final File toDir) throws IOException {
        String assetpath = (parentPath != null ? parentPath + File.separator + filename : filename);

        if (isDirectory(assetManager, assetpath)) {
            if (!toDir.exists()) {
                toDir.mkdirs();
                toDir.setExecutable(true, false);
            }
            for (String child : assetManager.list(assetpath)) {
                File nfile = new File(toDir, child);
                copyFiles(assetManager, assetpath, child, nfile);
                nfile.setReadable(true, false);
                nfile.setWritable(true, false);
            }
        } else {
            File nfile = new File(toDir.getParentFile(), filename);
            copyData(assetManager.open(assetpath), new FileOutputStream(nfile));
            nfile.setReadable(true, false);
            nfile.setWritable(true, false);
        }
    }

    private boolean isDirectory(AssetManager assetManager, final String path) throws IOException {
        boolean res = false;
        try {
            if (assetManager.list(path).length > 0){
                res = true;
            } else {
                assetManager.open(path);
            }
        } catch (FileNotFoundException fnfe) {
            res = true;
        }
        return res;
    }

    private void copyData(final InputStream in, final FileOutputStream out) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(in);

        try {
            writeData(bis, out);
        } finally {
            if (bis != null) {
               try {
                  bis.close();
              } catch (IOException ioe) {
                  String strError = "copyData: " + ioe.toString();
                  Log.i(LOGTAG, strError);
                 }
             }
        }
    }

    private void writeData(final InputStream is, final FileOutputStream os) throws IOException {
        BufferedOutputStream bos = null;

        try {
            bos = new BufferedOutputStream(os);
            byte[] buffer = new byte[BUFFER_SIZE];
            int len = 0;
            while ( (len = is.read(buffer, 0, buffer.length)) > 0) {
                bos.write(buffer, 0, len);
            }
            os.flush();
            os.getFD().sync();
        } finally {
            if (bos != null) { 
               try {
                   bos.close();
              } catch (IOException ioe) {
                    String strError = "writeData: " + ioe.toString();
                    Log.i(LOGTAG, strError);	
                }
             }
        }
    }

}
