package org.commcare.dalvik.activities;

import java.io.File;

import org.commcare.android.tasks.TemplatePrinterTask;
import org.commcare.android.tasks.TemplatePrinterTask.PopulateListener;
import org.commcare.dalvik.R;
import org.javarosa.core.reference.InvalidReferenceException;
import org.javarosa.core.reference.ReferenceManager;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.MimeTypeMap;

public class TemplatePrinterActivity extends Activity implements OnClickListener, PopulateListener {
    
    // TODO: stop using this hack
    private static final String TEMPLATE_FILE_TEMP_PATH = "jr://file/commcare/video/data/print_template.mp4";
    private static final String TEMPLATE_FILE_PATH = "jr://file/commcare/video/data/print_template.docx";

    @Override
    public void onClick(DialogInterface dialogInterface, int clickId) {

        // Error dialog "OK" click
        finish();

    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        Bundle data = getIntent().getExtras();
        
        if (data == null) {
            showErrorDialog(R.string.no_data);
            return;
        }
        
        try {
            File templateFile = new File(
                    ReferenceManager._().DeriveReference(TEMPLATE_FILE_PATH).getLocalURI()
            );
            File templateTempFile = new File(
                    ReferenceManager._().DeriveReference(TEMPLATE_FILE_TEMP_PATH).getLocalURI()
            );
            
            if (templateFile.exists() || templateTempFile.renameTo(templateFile)) {
    
                File outputFolder = templateFile.getParentFile();
    
                new TemplatePrinterTask(
                        templateFile,
                        outputFolder,
                        data,
                        this
                ).execute();
    
            } else {
                showErrorDialog(R.string.no_template);
            }
        } catch (InvalidReferenceException e) {
            showErrorDialog(e.getMessage());
        }
        
    }

    @Override
    public void onError(String message) {

        showErrorDialog(message);

    }

    @Override
    public void onFinished(File result) {

        startDocumentViewer(result);

        finish();

    }

    private void showErrorDialog(int messageResId) {
        showErrorDialog(getString(messageResId));
    }

    /**
     * Displays an error dialog with the specified message.
     * Activity will quit upon exiting the dialog.
     *
     * @param message Error message
     */
    private void showErrorDialog(String message) {

        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this)
                .setMessage(message)
                .setCancelable(false)
                .setPositiveButton(
                        R.string.ok,
                        this
                );

        dialogBuilder.show();

    }

    /**
     * Attempts to open the document with its default viewer.
     * If default viewer is unavailable, opens a dialog from which
     * a viewer application can be selected.
     *
     * @param document Document to open
     */
    private void startDocumentViewer(File document) {

        Uri uri = Uri.fromFile(document);

        String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
                MimeTypeMap.getFileExtensionFromUrl(
                        uri.toString()
                )
        );

        Intent intent = new Intent()
                .setAction(Intent.ACTION_VIEW)
                .setDataAndType(
                        uri,
                        type == null ? "*/*" : type
                );

        startActivity(intent);

    }

}

@@ -179,24 +179,79 @@
 teListener;%0A
+import org.commcare.android.util.TemplatePrinterUtils;%0A
 import org.c
@@ -760,24 +760,80 @@
 ener %7B%0A    %0A
+    private static final int REQUEST_TEMPLATE = 0;%0A    %0A
     // TODO:
@@ -896,28 +896,118 @@
 MPLATE_FILE_
-TEMP
+HACK_EXT = %22.mp4%22;%0A    // TODO: also support ODT%0A    private static final String TEMPLATE_FILE
 _PATH = %22jr:
@@ -1052,119 +1052,1249 @@
 ate.
-mp4
+docx
 %22;%0A    
-private static final String TEMPLATE_FILE_PATH = %22jr://file/commcare/video/data/print_template.docx%22;
+%0A    @Override%0A    protected void onActivityResult(int requestCode, int resultCode, Intent data) %7B%0A%0A        if (requestCode == REQUEST_TEMPLATE) %7B%0A%0A            if (resultCode == RESULT_OK%0A                    && data != null) %7B%0A%0A                Uri uri = data.getData();%0A                String extension = TemplatePrinterUtils.getExtension(uri.getPath());%0A%0A                if (TemplatePrinterTask.DocTypeEnum.isSupportedExtension(extension)) %7B%0A%0A                    File templateFile = new File(uri.getPath());%0A                    %0A                    File outputFolder = templateFile.getParentFile();%0A                    %0A                    new TemplatePrinterTask(%0A                            templateFile,%0A                            outputFolder,%0A                            getIntent().getExtras(),%0A                            this%0A                    ).execute();%0A%0A                %7D else %7B%0A                    showErrorDialog(%0A                            getString(%0A                                    R.string.file_invalid,%0A                                    uri.getPath()%0A                            )%0A                    );%0A                %7D%0A%0A            %7D else %7B%0A                finish();%0A            %7D%0A%0A        %7D%0A%0A    %7D
 %0A%0A  
@@ -2920,28 +2920,28 @@
 ile template
-Temp
+Hack
 File = new F
@@ -3020,17 +3020,37 @@
 ILE_
-TEMP_PATH
+PATH + TEMPLATE_FILE_HACK_EXT
 ).ge
@@ -3138,20 +3138,20 @@
 template
-Temp
+Hack
 File.ren
@@ -3472,32 +3472,33 @@
        %7D else %7B%0A
+%0A
                 
@@ -3502,45 +3502,43 @@
    s
-howErrorDialog(R.string.no_template);
+tartFileBrowser();%0A                
 %0A   
@@ -5306,21 +5306,383 @@
 y(intent);%0A%0A
+    %7D%0A    %0A    private void startFileBrowser() %7B%0A%0A        Intent chooseTemplateIntent = new Intent()%0A                .setAction(Intent.ACTION_GET_CONTENT)%0A                .setType(%22file/*%22)%0A                .addCategory(Intent.CATEGORY_OPENABLE);%0A%0A        startActivityForResult(%0A                chooseTemplateIntent,%0A                REQUEST_TEMPLATE%0A        );%0A%0A
     %7D%0A%0A%7D%0A

Add file browser when no template found