/**
 *    Copyright 2014 Galois, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.galois.qrstream.lib;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.galois.qrstream.qrpipe.IProgress;
import com.galois.qrstream.qrpipe.Receive;
import com.galois.qrstream.qrpipe.ReceiveException;

import org.jetbrains.annotations.NotNull;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;

/**
 * Created by donp on 2/28/14.
 */
public class DecodeThread extends Thread {
    private final Receive receiver;
    private final CameraManager cameraManager;
    private final Context context;

    public DecodeThread(Context ctx, IProgress progress, CameraManager cameraManager) {
        this.context = ctx;
        this.cameraManager = cameraManager;
        this.receiver = new Receive(
                cameraManager.getDisplayHeight(),
                cameraManager.getDisplayWidth(),
                progress);
    }

    @Override
    public void run(){
        Job message;
        try {
            message = (Job)receiver.decodeQRSerializable(cameraManager);
            Log.w(Constants.APP_TAG, "DecodeThread read message of length: " + message.getData().length);
            Log.w(Constants.APP_TAG, "DecodeThread heard " + message.toString());


            Intent i = new Intent();
            i.setAction(Intent.ACTION_SEND);
            i.addCategory(Intent.CATEGORY_DEFAULT);
            i.setType(message.getMimeType());

            // this should conditionally use a URI if the payload is too large.
            URI dataLoc = storeData(message);
            i.putExtra(Intent.EXTRA_STREAM, dataLoc);

            // TODO integrate with ZXing

            context.startActivity(Intent.createChooser(i, "Open with"));
        } catch(ReceiveException e) {
            Log.e(Constants.APP_TAG, "DecodeThread failed to read message. " + e.getMessage());
        } catch (IOException e) {
            Log.e(Constants.APP_TAG, "Could not store data to temp file." + e.getMessage());
        }
    }

    private @NotNull URI storeData(Job message) throws IOException {
        File cacheDir = context.getCacheDir();
        File tmpFile = File.createTempFile("qrstream","", cacheDir);

        // make tmpFile world-readable:
        tmpFile.setReadable(true, false);
        tmpFile.deleteOnExit();

        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(new FileOutputStream(tmpFile));
            bos.write(message.getData());
            bos.flush();
        } finally {
            if ( null != bos) {
                bos.close();
            }
        }
        return tmpFile.toURI();
    }
}

@@ -1773,29 +1773,14 @@
 d re
-ad message of length:
+ceived
  %22 +
@@ -1808,251 +1808,60 @@
 ngth
-);%0A            Log.w(Constants.APP_TAG, %22DecodeThread heard %22 + message.toString());%0A%0A%0A            Intent i = new Intent();%0A            i.setAction(Intent.ACTION_SEND);%0A            i.addCategory(Intent.CATEGORY_DEFAULT);%0A            i.setType(
+ + %22 bytes %22 +%0A                                     
 mess
@@ -1880,17 +1880,16 @@
 ype());%0A
-%0A
         
@@ -1896,173 +1896,133 @@
     
-// this should conditionally use a URI if the payload is too large.%0A            URI dataLoc = storeData(message);%0A            i.putExtra(Intent.EXTRA_STREAM, dataLoc
+Log.w(Constants.APP_TAG, %22DecodeThread heard %22 + new String(message.getData()));%0A%0A%0A            Intent i = buildIntent(message
 );%0A%0A
@@ -2410,24 +2410,670 @@
    %7D%0A    %7D%0A%0A
+    private Intent buildIntent(Job message) throws IOException %7B%0A        Intent i = new Intent();%0A        i.setAction(Intent.ACTION_SEND);%0A        i.addCategory(Intent.CATEGORY_DEFAULT);%0A        String mimeType = message.getMimeType();%0A        i.setType(mimeType);%0A%0A        if(mimeType.equals(%22text/plain%22)) %7B%0A            String msg = new String(message.getData());%0A            i.putExtra(Intent.EXTRA_TEXT, msg);%0A        %7D else %7B%0A            // this should conditionally use a URI if the payload is too large.%0A            URI dataLoc = storeData(message);%0A            i.putExtra(Intent.EXTRA_STREAM, dataLoc);%0A        %7D%0A        return i;%0A    %7D%0A%0A
     private 

use EXTRA_TEXT when receiving text