package com.galois.qrstream;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.ContentResolver;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import com.galois.qrstream.lib.Constants;
import com.galois.qrstream.lib.Job;
import com.galois.qrstream.lib.ReceiveFragment;
import com.galois.qrstream.lib.TransmitFragment;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class MainActivity extends Activity {

    private FragmentManager fragmentManager;
    private List<Job> jobsList;
    protected ReceiveFragment receiveFragment; // accessed via unittest
    protected TransmitFragment transmitFragment; // accessed via unittest

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        jobsList = (List)new ArrayList();
        fragmentManager = getFragmentManager();
        receiveFragment = new ReceiveFragment();
        transmitFragment = new TransmitFragment(jobsList);

        if (savedInstanceState == null) {
            Intent startingIntent = getIntent();
            Log.d(Constants.APP_TAG, "startingIntent  " + startingIntent.getAction());
            if(startingIntent.getAction() == Intent.ACTION_SEND) {
                Job job = buildJobFromIntent(startingIntent);
                jobsList.add(job);
                showFragment(transmitFragment);
            } else {
                showFragment(receiveFragment);
            }
        }
    }

    private void showFragment(Fragment fragment) {
        fragmentManager.beginTransaction()
                .replace(R.id.container, fragment)
                .commit();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }

        if (id == R.id.action_receive) {
            showFragment(receiveFragment);
            return true;
        }
        if (id == R.id.action_transmit) {
            showFragment(transmitFragment);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private String getNameFromURI(Uri uri) {
        String name;
        Cursor metadata = getContentResolver().query(uri,
                                                     new String[] {OpenableColumns.DISPLAY_NAME},
                                                     null, null, null);
        if(metadata != null && metadata.moveToFirst()) {
            name = metadata.getString(0);
        } else {
            name = uri.getLastPathSegment();
        }
        return name;
    }

    private byte[] readFileUri(Uri uri) {
        ContentResolver contentResolver = getContentResolver();
        try {
            AssetFileDescriptor fd = contentResolver.openAssetFileDescriptor(uri, "r");
            long fileLength = fd.getLength();
            Log.d("qrstream","fd length "+fileLength);
            DataInputStream istream = new DataInputStream(contentResolver.openInputStream(uri));
            byte[] buf = new byte[(int)fileLength];
            istream.readFully(buf);
            return buf;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private Job buildJobFromIntent(Intent intent) {
        String type = intent.getType();
        Bundle extras = intent.getExtras();
        Log.d("qrstream", "** received type "+type);

        String name = "";
        byte[] bytes = null;

        Uri dataUrl = (Uri) intent.getExtras().getParcelable(Intent.EXTRA_STREAM);
        if(dataUrl != null) {
            if (dataUrl.getScheme().equals("content")) {
                name = getNameFromURI(dataUrl);
                bytes = readFileUri(dataUrl);
            }
        } else {
            // fall back to content in extras (mime type dependent)
            if(type.equals("text/plain")) {
                String body = extras.getString(Intent.EXTRA_SUBJECT) +
                              extras.getString(Intent.EXTRA_TEXT);
                bytes = body.getBytes();
            }
        }
        return new Job(name, bytes);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            return rootView;
        }
    }


}

@@ -1545,14 +1545,8 @@
 t = 
-(List)
 new 
@@ -1554,16 +1554,21 @@
 rrayList
+%3CJob%3E
 ();%0A    
@@ -3837,35 +3837,54 @@
 FileUri(Uri uri)
+ throws IOException
  %7B%0A
-
         ContentR
@@ -3935,26 +3935,8 @@
 ();%0A
-        try %7B%0A    
     
@@ -4023,20 +4023,16 @@
         
-   
- 
 long fil
@@ -4053,28 +4053,24 @@
 etLength();%0A
-    
         Log.
@@ -4116,20 +4116,16 @@
         
-  
-  
 DataInpu
@@ -4205,28 +4205,24 @@
 ));%0A        
-    
 byte%5B%5D buf =
@@ -4257,20 +4257,16 @@
         
-    
 istream.
@@ -4281,20 +4281,16 @@
 y(buf);%0A
-    
         
@@ -4305,183 +4305,8 @@
 uf;%0A
-        %7D catch (FileNotFoundException e) %7B%0A            e.printStackTrace();%0A        %7D catch (IOException e) %7B%0A            e.printStackTrace();%0A        %7D%0A        return null;%0A
     
@@ -4720,24 +4720,50 @@
 ontent%22)) %7B%0A
+                try %7B%0A    
             
@@ -4806,32 +4806,36 @@
                 
+    
 bytes = readFile
@@ -4840,32 +4840,178 @@
 leUri(dataUrl);%0A
+                %7D catch (IOException e) %7B%0A                    // todo: Handle IO error%0A                    e.printStackTrace();%0A                %7D%0A
             %7D%0A  

rework exception handling