package com.usai.redant.redantmobile;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.usai.redant.CommonEditor.CommonEditorActivity;
import com.usai.redant.Result.SearchResultActivity;
import com.usai.redant.Search.RamSearchActivity;
import com.usai.redant.Search.RamSearchSettingActivity;
import com.usai.redant.raimage.ModeActivity;

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

public class ModeListActivity extends AppCompatActivity {

    private JSONArray mModeList;
    private ListView mListView;
    private ModeAdapter mAdapter;
    private Context mContext;
    private boolean isRoot;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mode_list);
        mContext = this;

        isRoot = getIntent().getBooleanExtra("isRoot",false);


        String modeList_string;
        String title;
        if (savedInstanceState == null) {
            modeList_string = getIntent().getStringExtra("mode_list");
            title = getIntent().getStringExtra("title");
        } else {
            modeList_string = savedInstanceState.getString("mode_list");
            title = savedInstanceState.getString("title");
        }

        if (title != null) {
            setTitle(title);
        }

        if (modeList_string != null && !modeList_string.isEmpty()) {
            try {
                mModeList = new JSONArray(modeList_string);
                Log.d("Mode List", "onCreate: ");
            } catch (JSONException e) {
                mModeList = null;
                e.printStackTrace();
            }
        } else {
            mModeList = null;
        }

        mListView = (ListView)findViewById(R.id.ram_mode_list_view);
        mAdapter = new ModeAdapter();
        mListView.setAdapter(mAdapter);

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                JSONObject modeItem = (JSONObject) mAdapter.getItem(i);
                String type = modeItem.optString("type");
                if (type != null) {
                    if (type.equals("predef_query")) {

                        processPredefQuery(modeItem);

                    } else if (type.equals("query")) {

                        processQuery(modeItem);

                    } else if (type.equals("local_func")) {

                        processLocalFunc(modeItem);

                    } else if (type.equals("submode")) {

                        processSubmode(modeItem);

                    }
                }
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (isRoot) {
            getMenuInflater().inflate(R.menu.logout_menu,menu);

            return true;
        } else {
            return super.onCreateOptionsMenu(menu);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.logout_item: {
                logout();
            }
            break;
        }
        return true;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        if (mModeList != null) {
            outState.putString("mode_list",mModeList.toString());
        }

        CharSequence title = getTitle();
        if (title != null) {
            outState.putString("title",title.toString());
        }
    }


    void logout() {
        RedAntApplication.user = null;
        RedAntApplication.password = null;
        RedAntApplication.server_info = null;
        Intent intent = new Intent(mContext,LoginActivity.class);
        startActivity(intent);
        finish();
    }


    private void processPredefQuery(JSONObject modeInfo) {
        try {
            String query_id = modeInfo.getString("query_id");
            String title = modeInfo.optString("title");

            Intent intent = new Intent(mContext, SearchResultActivity.class);

            Bundle bundle = new Bundle();
            bundle.putString("query_id",query_id);

            if (title != null) {
                bundle.putString("title",title);
            }
            intent.putExtra("query_params",bundle);

            startActivity(intent);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void processQuery(JSONObject modeInfo) {
        try {
            String title = modeInfo.optString("title");
            String query_id = modeInfo.getString("query_id");

            Bundle bundle = new Bundle();
            if (title != null) {
                bundle.putString("title",title);
            }
            bundle.putString("query_id",query_id);

            Intent intent = new Intent(mContext, RamSearchActivity.class);
            intent.putExtra("params",bundle);
            intent.putExtra("request_url",RedAntApplication.server);
            intent.putExtra("url_type", CommonEditorActivity.URL_REMOTE);

            startActivity(intent);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void processLocalFunc(JSONObject modeInfo) {
        try {
//            String title = modeInfo.getString("title");
            String module = modeInfo.getString("module");

            if (module != null) {

                if (module.equals("tools_change_pwd")) {
                    Log.d("Mode List", "processLocalFunc: change password");
                } else if (module.equals("raimage_mode")) {

                    JSONObject serverinfo = new JSONObject();
                    JSONArray mode_list = modeInfo.getJSONArray("ext_data");
                    serverinfo.put("modellist",mode_list);
                    RedAntApplication.server_info = serverinfo;

                    Intent intent = new Intent(mContext, ModeActivity.class);
                    startActivity(intent);
                }

            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void processSubmode(JSONObject modeInfo) {
        try {

            Intent intent = new Intent(mContext,ModeListActivity.class);

            JSONArray mode_list = modeInfo.getJSONArray("mode_list");
            String title = modeInfo.getString("name");

            intent.putExtra("mode_list",mode_list.toString());
            intent.putExtra("title",title);

            startActivity(intent);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    private class ModeAdapter extends BaseAdapter {

        private class ModeViewHolder {
            TextView name_lb;
            ImageButton setting_btn;
            int position;
            ModeViewHolder(View cell) {
                name_lb = (TextView)cell.findViewById(R.id.ram_mode_name_lb);
                setting_btn = (ImageButton)cell.findViewById(R.id.ram_mode_setting_btn);
                cell.setTag(this);

                setting_btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        JSONObject modeItem = (JSONObject) getItem(position);

                        try {

                            String title = modeItem.optString("name");
                            String query_id = modeItem.getString("query_id");

                            Bundle bundle = new Bundle();
                            if (title != null) {
                                bundle.putString("title",title);
                            }
                            bundle.putString("query_id",query_id);

                            Intent intent = new Intent(mContext, RamSearchSettingActivity.class);
                            intent.putExtra("params",bundle);
                            intent.putExtra("request_url",RedAntApplication.server);
                            intent.putExtra("url_type", CommonEditorActivity.URL_REMOTE);

                            startActivity(intent);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });
            }
        }

        @Override
        public int getCount() {
            if (mModeList == null) {
                return 0;
            }
            return mModeList.length();
        }

        @Override
        public Object getItem(int i) {
            if (mModeList == null) {
                return null;
            }
            return mModeList.opt(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {

            View cell = null;
            ModeViewHolder holder = null;
            if (view == null) {

                cell = LayoutInflater.from(mContext).inflate(R.layout.ram_mode_cell,null);
                holder = new ModeViewHolder(cell);

            } else {

                cell = view;
                holder = (ModeViewHolder)cell.getTag();

            }

            JSONObject modeItem = (JSONObject) getItem(i);
            String type = modeItem.optString("type");
            if (type != null && type.equals("query")) {
                holder.setting_btn.setVisibility(View.VISIBLE);
            } else {
                holder.setting_btn.setVisibility(View.INVISIBLE);
            }

            String name = modeItem.optString("name");
            String desc = modeItem.optString("description");
            if (desc == null || desc.isEmpty() || name == null || name.isEmpty()) {
                holder.name_lb.setText(name);
            } else {
                String str = name + " -- " + desc;
                Spannable span = new SpannableString(str);
                    /* 设置字体大小
                     * AbsoluteSizeSpan: boolean dip，如果为true，表示前面的字体大小单位为dip，否则为像素
                     * start:
                     * end:
                     * 区间开闭:
                     */
                span.setSpan(new AbsoluteSizeSpan(15,true),name.length() + 1,str.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                    /* 设置字体颜色
                     *
                     */
                span.setSpan(new ForegroundColorSpan(Color.RED),name.length() + 1,str.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                span.setSpan(new AbsoluteSizeSpan(17,true), 0, name.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                span.setSpan(new ForegroundColorSpan(Color.BLACK),0,name.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                holder.name_lb.setText(span);
            }

            holder.position = i;

            return cell;
        }
    }
}
