package jp.sourceforge.tamanegisoul.sa.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Environment;

public class ErrorReporter {

    private static final File LOG_DIR = new File(Environment.getExternalStorageDirectory(), "Mezamashi");
    private static final File LOG_FILE = new File(LOG_DIR, "log");

    public static boolean isErrorOccured() {
        return LOG_FILE.exists();
    }

    public static void storeError(Throwable throwable) {
        PrintWriter out = null;
        try {
            LOG_FILE.getParentFile().mkdirs();
            out = new PrintWriter(new FileOutputStream(LOG_FILE));
            throwable.printStackTrace(out);
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    private static String readErrorMessage() {
        BufferedReader r;
        StringBuilder buffer = new StringBuilder();
        try {
            r = new BufferedReader(new FileReader(LOG_FILE));
            for (String read = r.readLine(); read != null; read = r.readLine()) {
                buffer.append(read).append("\n");
            }
            r.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

    private static void deleteErrorFile() {
        LOG_FILE.delete();
        LOG_DIR.delete();
    }

    public static void showConfirmDialog(final Activity parent) {
        if (ErrorReporter.isErrorOccured()) {
            AlertDialog.Builder builder = new AlertDialog.Builder(parent);
            builder.setTitle("エラー報告");
            builder.setMessage("前回動作中に強制終了しました。エラー情報収集にご協力ください。");
            builder.setNegativeButton("送信しない", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    showExitDialog(parent);
                }
            });
            builder.setPositiveButton("送信する", new DialogInterface.OnClickListener() {
                public void onClick(final DialogInterface dialog, int which) {
                    try {
                        final List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                        String bug = ErrorReporter.readErrorMessage();
                        nvps.add(new BasicNameValuePair("device", Build.DEVICE));
                        nvps.add(new BasicNameValuePair("model", Build.MODEL));
                        nvps.add(new BasicNameValuePair("sdkVersion", Build.VERSION.SDK));
                        PackageInfo i = parent.getPackageManager().getPackageInfo(parent.getPackageName(), 0);
                        nvps.add(new BasicNameValuePair("appName", "メザマシ！"));
                        nvps.add(new BasicNameValuePair("appVersion", i.versionName));
                        nvps.add(new BasicNameValuePair("message", bug));

                        final ProgressDialog progressDialog = new ProgressDialog(parent);
                        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                        progressDialog.setMessage("送信中…");
                        progressDialog.setCancelable(true);
                        progressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                showExitDialog(parent);
                            }
                        });
                        progressDialog.show();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    HttpPost httpPost = new HttpPost("http://errorreportts.appspot.com/errorreport");
                                    httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
                                    DefaultHttpClient httpClient = new DefaultHttpClient();
                                    httpClient.execute(httpPost);
                                    progressDialog.dismiss();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }).start();
                    } catch (NameNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            });
            builder.show();
        }
    }

    private static void showExitDialog(final Activity parent) {
        deleteErrorFile();
        AlertDialog.Builder builder = new AlertDialog.Builder(parent);
        builder.setMessage("アプリケーションを終了します。再度起動してみてください。");
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface arg0) {
                parent.finish();
            }
        });
        dialog.show();
    }

}
