package jp.sourceforge.nicoro;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.io.File;

import jp.gr.java_conf.shiseissi.commonlib.DialogFragmentEx;
import jp.gr.java_conf.shiseissi.commonlib.FileSelectFragment;
import jp.gr.java_conf.shiseissi.commonlib.SimpleMessageDialogFragment;
import jp.gr.java_conf.shiseissi.commonlib.ViewUtil;

public class SelectCacheDirActivity extends FragmentActivity
implements FileSelectFragment.EventListener {
    private static final String LOG_TAG = "FileUtil";

    private Context mContext;

    private TextView mDirFreeSpace;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mContext = getApplicationContext();

        setContentView(R.layout.select_cache_dir);

        mDirFreeSpace = ViewUtil.findViewById(this, R.id.dir_free_space);

        if (savedInstanceState == null) {
            FileSelectFragment.StringResourceParams params = new FileSelectFragment.StringResourceParams();
            params.moveButton = R.string.move;
            params.makeDirMenu = R.string.menu_make_dir;
            params.makeDirTitle = R.string.menu_make_dir;
            params.makeDirHint = R.string.hint_input_new_dir;
            params.makeDirSucceed = R.string.toast_make_dir_succeed;
            params.makeDirFail = R.string.toast_make_dir_fail;
            String dir = VideoLoader.getStreamTempDir(getApplicationContext());
            File file = new File(dir);
            if (!file.isDirectory()) {
                file.mkdirs();
            }
            FileSelectFragment fileSelect = FileSelectFragment.newInstance(true,
                    dir, params);
            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            ft.add(R.id.file_select_fragment, fileSelect).commit();

            ft = fm.beginTransaction();
            Fragment prev = fm.findFragmentByTag("dialog");
            if (prev != null) {
                ft.remove(prev);
            }
            ft.addToBackStack(null);
            SimpleMessageDialogFragment dialog = SimpleMessageDialogFragment.newInstance(
                    R.string.dialog_message_select_cache_dir_catution,
                    R.string.caution, android.R.drawable.ic_dialog_alert);
            dialog.show(ft, "dialog");
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.select_cache_dir, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_move_default_dir:
                FragmentManager fm = getSupportFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                Fragment prev = fm.findFragmentByTag("dialog");
                if (prev != null) {
                    ft.remove(prev);
                }
                ft.addToBackStack(null);
                MoveDefaultDirDialogFragment dialogFragment = new MoveDefaultDirDialogFragment();
                dialogFragment.show(ft, "dialog");
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onOk(FileSelectFragment fragment, String filePath) {
        if (isPathOkForCache(filePath)) {
            SharedPreferences sharedPreference = Util.getDefaultSharedPreferencesMultiProcess(this);
            final String prefKeySelectCacheDir = getString(
                    R.string.pref_key_select_cache_dir);
            SharedPreferences.Editor editor = sharedPreference.edit();
            String oldCacheDirPath = sharedPreference.getString(prefKeySelectCacheDir,
                    null);
            editor.putString(prefKeySelectCacheDir, filePath);
            editor.commit();

            if (isCacheNeededToMove(filePath, oldCacheDirPath)) {
                // 既にあるキャッシュファイルの移動
                new AsyncTask<String, Void, Void>() {
                    private ProgressDialog progressDialog;

                    @Override
                    protected void onPreExecute() {
                        ProgressDialog pd = Util.createProgressDialogLoading(
                                SelectCacheDirActivity.this,
                                R.string.toast_cache_moving, null);
                        pd.show();
                        progressDialog = pd;
                    }

                    @Override
                    protected Void doInBackground(String... params) {
                        String newCacheDirPath = params[0];
                        String oldCacheDirPath = params[1];
                        VideoLoader.moveCacheFiles(newCacheDirPath, oldCacheDirPath);
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void result) {
                        ProgressDialog pd = progressDialog;
                        progressDialog = null;
                        if (pd != null) {
                            pd.dismiss();
                        }

                        Util.showInfoToast(mContext,
                                R.string.toast_select_cache_dir_succeed);
                        finish();
                    }
                }.execute(filePath, oldCacheDirPath);
            } else {
                Util.showInfoToast(mContext,
                        R.string.toast_select_cache_dir_succeed);
                finish();
            }
        } else {
            Util.showErrorToast(mContext, R.string.toast_select_cache_dir_fail);
        }

    }

    @Override
    public void onCancel(FileSelectFragment fragment) {
        finish();
    }

    @Override
    public void onChangeDirectory(FileSelectFragment fragment, String dir) {
        StorageInfo storageInfo = new StorageInfo(dir);
        String size = storageInfo.getAvailable();
        String text = getString(R.string.dir_free_space, size);
        mDirFreeSpace. setText(text);
    }

    private boolean isPathOkForCache(String filePath) {
        File dir = new File(filePath);

        // 一部のディレクトリは却下
        if (dir.equals(new File(File.separator))) {
            return false;
        } else if (dir.equals(Environment.getExternalStorageDirectory())) {
            return false;
        } else if (dir.equals(new File(File.separator + "sdcard"))) {
            return false;
        }

        return true;
    }

    private boolean isCacheNeededToMove(String newCacheDirPath,
            String oldCacheDirPath) {
        if (oldCacheDirPath == null) {
            return false;
        }
        File oldCacheDir = new File(oldCacheDirPath);
        if (!oldCacheDir.exists()) {
            return false;
        }
        if (oldCacheDir.equals(new File(newCacheDirPath))) {
            return false;
        }
        return true;
    }

    public static class MoveDefaultDirDialogFragment extends DialogFragmentEx {
        public MoveDefaultDirDialogFragment() {
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            Activity activity = getActivity();

            final String[] defaultDirs = new String[] {
                    VideoLoader.getStreamTempDirDefault(activity),
                    VideoLoader.STREAM_TEMP_DIR_OLD_VERSION
            };
            String[] listItems = new String[] {
                    activity.getString(R.string.listitem_default_dir_new,
                            defaultDirs[0]),
                    activity.getString(R.string.listitem_default_dir_old,
                            defaultDirs[1])
            };
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                    activity, android.R.layout.simple_list_item_1, listItems);

            AlertDialog.Builder builder = new AlertDialog.Builder(activity)
                .setAdapter(adapter, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which < 0 || which >= defaultDirs.length) {
                            Log.e(LOG_TAG, Log.buf()
                                    .append("MoveToDefaultDir invalid value: ")
                                    .append(which).toString());
                            return;
                        }

                        String dir = defaultDirs[which];
                        File dirFile = new File(dir);
                        if (!dirFile.exists()) {
                            dirFile.mkdirs();
                        }
                        if (!dirFile.isDirectory()) {
                            Log.e(LOG_TAG, Log.buf()
                                    .append("mkdir failed: ")
                                    .append(dir).toString());
                            return;
                        }

                        FileSelectFragment fileSelect = ViewUtil.findFragmentById(
                                getFragmentManager(),
                                R.id.file_select_fragment);
                        if (fileSelect != null) {
                            fileSelect.setDirectory(dir);
                        }
                    }
                })
                .setCancelable(true)
                .setNegativeButton(android.R.string.cancel, null);
            return builder.create();
        }
    }
}
