package jp.sourceforge.nicoro;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewStub;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import jp.gr.java_conf.shiseissi.commonlib.DialogFragmentEx;
import jp.gr.java_conf.shiseissi.commonlib.ViewUtil;
import static jp.sourceforge.nicoro.Log.LOG_TAG;
import static jp.sourceforge.nicoro.NicoroAPIManager.ECO_TYPE_HIGH;
import static jp.sourceforge.nicoro.NicoroAPIManager.ECO_TYPE_MID;
import static jp.sourceforge.nicoro.NicoroAPIManager.ECO_TYPE_LOW;

public class StartPlaylistDialogFragment extends DialogFragmentEx
implements AdapterView.OnItemClickListener {
    private static final boolean DEBUG_LOGD = Release.IS_DEBUG & true;

    private static final String KEY_MYLIST_NUMBER = "KEY_MYLIST_NUMBER";

    private static class ResInteger {
        private static int playlist_eco_normal;
        private static int playlist_eco_mid;
        private static int playlist_eco_low;
    }

    private Context mContext;

    private View mViewRoot;
    private Spinner mSpinnerEcoType;
    private ListView mListSort;

    private String mMylistNumber;

    private AsyncStartPlaylist mAsyncStartPlaylist = null;
    private class AsyncStartPlaylist extends NicoJSONCustomLoader {
        private int mSortOrder;
        private int mEcoType;
        AsyncStartPlaylist(Context context, int sortOrder, int ecoType) {
            super(context);
            mSortOrder = sortOrder;
            mEcoType = ecoType;
        }

        @Override
        protected void onPostExecute(ChangeReference<JSONObject> result) {
            super.onPostExecute(result);

            mAsyncStartPlaylist = null;

            Activity activity = getActivity();
            if (activity == null) {
                if (DEBUG_LOGD) {
                    Log.d(LOG_TAG, "AsyncStartPlay#onPostExecute: StartPlaylistDialogFragment was removed");
                }
            } else {
                JSONObject json;
                if (result != null) {
                    json = result.get();
                    result.weaken();
                } else {
                    json = null;
                }
                if (json != null) {
                    try {
                        // TODO
                        if (DEBUG_LOGD) {
                            Log.d(LOG_TAG, "getplaylist result:");
                            Log.dLines(LOG_TAG, json.toString(2));
                        }

                        SharedPreferences sp = Util.getDefaultSharedPreferencesMultiProcess(mContext);
                        String cookieUserSession =
                            NicoroConfig.getCookieUserSession(sp);
                        String userId = null;
                        if (cookieUserSession != null) {
                            Matcher matcher = Pattern.compile(
                                    WebBrowserFragment.PATTERN_GET_USERID_FROM_USERSESSION)
                                    .matcher(cookieUserSession);
                            userId = Util.getFirstMatch(matcher);
                        }

                        Intent intent = NicoroAPIManager.createPlaylistPlayerIntent(
                                mContext, json, mSortOrder, mEcoType, cookieUserSession, userId);
                        startActivity(intent);

                        if (activity instanceof EventListener) {
                            ((EventListener) activity).onStartPlaylistExecuted(
                                    StartPlaylistDialogFragment.this);
                        }

                        dismissSafely();
                        return;
                    } catch (JSONException e) {
                        Log.w(LOG_TAG, e.toString(), e);
                    } catch (IOException e) {
                        Log.w(LOG_TAG, e.toString(), e);
                    }
                }
                // エラー
                String message = mContext.getString(
                        R.string.errormessage_play_fail_unknown);
                Util.showErrorDialog(activity,
                        message,
                        false);
            }

            dismissSafely();
        }
    }

    public static StartPlaylistDialogFragment createInstance(String mylistNumber) {
        StartPlaylistDialogFragment fragment = new StartPlaylistDialogFragment();
        Bundle args = new Bundle(1);
        args.putString(KEY_MYLIST_NUMBER, mylistNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public StartPlaylistDialogFragment() {
    }

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

        mContext = getActivity().getApplicationContext();

        Resources res = mContext.getResources();
        ResInteger.playlist_eco_normal = res.getInteger(R.integer.playlist_eco_normal);
        ResInteger.playlist_eco_mid = res.getInteger(R.integer.playlist_eco_mid);
        ResInteger.playlist_eco_low = res.getInteger(R.integer.playlist_eco_low);

        Bundle args = getArguments();
        if (args != null) {
            mMylistNumber = args.getString(KEY_MYLIST_NUMBER);
        }

        if (mMylistNumber == null) {
            Util.showErrorToast(mContext, R.string.errormessage_unknown);
            dismissSafely();
        }
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        ContextThemeWrapper context = new ContextThemeWrapper(getActivity(),
                R.style.Theme_Dialog);
        LayoutInflater inflater = LayoutInflater.from(context);

        View view = inflater.inflate(R.layout.start_playlist_dialog, null);
        mViewRoot = view;
        Spinner spinnerEcoType = ViewUtil.findViewById(view, R.id.eco_type);
        mSpinnerEcoType = spinnerEcoType;
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                context, R.array.playlist_eco, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerEcoType.setAdapter(adapter);
        spinnerEcoType.setSelection(ResInteger.playlist_eco_normal);

        ListView listSort = ViewUtil.findViewById(view, android.R.id.list);
        mListSort = listSort;
        adapter = ArrayAdapter.createFromResource(
                context, R.array.mylist_sort, android.R.layout.simple_list_item_1);
        listSort.setAdapter(adapter);
        listSort.setOnItemClickListener(this);

        return new AlertDialog.Builder(getActivity())
            .setTitle(R.string.dialog_title_playlist)
            .setView(view)
            .setCancelable(true)
            .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (mAsyncStartPlaylist != null) {
                        mAsyncStartPlaylist.cancel(false);
                    }
                }
            })
            .setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    if (mAsyncStartPlaylist != null) {
                        mAsyncStartPlaylist.cancel(false);
                    }
                }
            })
            .create();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        int ecoType;
        int pos = mSpinnerEcoType.getSelectedItemPosition();
        if (pos == ResInteger.playlist_eco_normal) {
            ecoType = ECO_TYPE_HIGH;
        } else if (pos == ResInteger.playlist_eco_mid) {
            ecoType = ECO_TYPE_MID;
        } else if (pos == ResInteger.playlist_eco_low) {
            ecoType = ECO_TYPE_LOW;
        } else {
            assert false;
            // とりあえず通常画質
            ecoType = ECO_TYPE_HIGH;
        }

        int sortOrder = position;

        // playlist取得
        ViewUtil.removeViewFromParent(mSpinnerEcoType);
        ViewUtil.removeViewFromParent(mListSort);
        ViewStub stubProgress = ViewUtil.findViewById(mViewRoot, R.id.stub_progress);
        stubProgress.inflate();

        mAsyncStartPlaylist = new AsyncStartPlaylist(mContext, sortOrder, ecoType);
        NicoroAPIManager.executePlaylistJSONLoader(mAsyncStartPlaylist,
                mMylistNumber);
    }

    public interface EventListener {
        void onStartPlaylistExecuted(StartPlaylistDialogFragment fragment);
    }
}
