package com.usai.redant.raimage;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
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.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.usai.redant.raimage.Model.ModelActivity;
import com.usai.redant.raimage.POP.PopActivity;
import com.usai.redant.redantmobile.LoginActivity;
import com.usai.redant.redantmobile.R;
import com.usai.redant.redantmobile.RedAntApplication;
import com.usai.redant.util.Network;
import com.usai.redant.util.RAUtil;

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

import java.util.ArrayList;
import java.util.List;

//import com.usai.redant.util.Network;

public class ModeActivity extends AppCompatActivity {

    private ListView mode_list;
    private Button upload_setting_btn;
    private ImageView company_icon_iv;
    private TextView company_name_tv;
    private List<JSONObject> dataSource;
    private ModeAdapter adapter;
    /** Message Handler */
    private Handler msgHanlder = new Handler() {

        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1024:{
                    company_icon_iv.setImageBitmap((Bitmap)msg.obj);
                }
            }
        }

    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mode);

        /**获取控件*/
        mode_list = (ListView)findViewById(R.id.mode_list);
        upload_setting_btn = (Button)findViewById(R.id.upload_setting_btn);
        company_icon_iv = (ImageView)findViewById(R.id.company_name_icon);
        company_name_tv = (TextView)findViewById(R.id.company_name_text);

        /**设置数据*/
        try {

            // company
            final String icon_link = RedAntApplication.server_info.optString("company_icon");
            String company_name = RedAntApplication.server_info.optString("company_name");

            if (!TextUtils.isEmpty(company_name)) {
                company_name_tv.setText(company_name);
            }

            if (!TextUtils.isEmpty(icon_link)) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        // http://192.168.0.130/bo.png
                        Bitmap img = Network.getImageFromLink(icon_link);
                        if (img != null) {
                            Message msg = new Message();
                            msg.what = 1024;
                            msg.obj = img;
                            msgHanlder.sendMessage(msg);
                        }
                    }
                }).start();
            }

            // mode list
            JSONArray modeArr = RedAntApplication.server_info.getJSONArray("modellist");
            if (modeArr.length() > 0) {
                dataSource = new ArrayList<JSONObject>();
                for (int i = 0; i < modeArr.length();i++) {
                    JSONObject obj = modeArr.getJSONObject(i);
                    dataSource.add(obj);
                }
                adapter = new ModeAdapter(this,R.layout.mode_cell,dataSource);
                mode_list.setAdapter(adapter);
            }

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

        /**List View 点击事件*/
        mode_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                JSONObject mode = dataSource.get(position);
               try {
                   int enable = mode.getInt("enable");
                   if (enable != 0) {
                       showActivityMode(mode);
                   }

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

            }
        });

        /**上传设置按钮点击*/
        upload_setting_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showUploadSetting();
            }
        });
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        String appName = RAUtil.getApplicationName(this);
        if (appName.equals("RedAnt Mobile")) {

            return super.onCreateOptionsMenu(menu);

        } else {
            getMenuInflater().inflate(R.menu.logout_menu,menu);
            return true;
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.logout_item: {
//                Log.d("Mode List", "Menu Item Click " + item.getTitle());
                logout();
            }
                break;
        }
        return true;
    }

    /***/
    void showActivityMode(JSONObject mode) {

       try {
           String name = mode.getString("name");

           String code_name = mode.getString("code_name");
           if (name.equals("POP")) {
               Intent intent = new Intent(this,PopActivity.class);
               intent.putExtra("mode","POP");
               intent.putExtra("name",code_name);
               startActivity(intent);
           } else if (name.equals("Model")) {
               Intent intent = new Intent(this,ModelActivity.class);
               intent.putExtra("mode","Model");
               intent.putExtra("name",code_name);
               startActivity(intent);
           }
           else  if (name.equals("Receiving")) {
               Intent intent = new Intent(this,PopActivity.class);
               intent.putExtra("mode","Receiving");
               intent.putExtra("name",code_name);
               startActivity(intent);
           }
           else  if (name.equals("Returns")) {
               Intent intent = new Intent(this,PopActivity.class);
               intent.putExtra("mode","Returns");
               intent.putExtra("name",code_name);
               startActivity(intent);
           }
       } catch (Exception e) {
           e.printStackTrace();
       }

    }

    /**上传设置*/
    void showUploadSetting() {
        Intent intent = new Intent(ModeActivity.this,uploadSettingActivity.class);
        startActivity(intent);
    }

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

    /**数据源*/
    class ModeAdapter extends ArrayAdapter<JSONObject> {
        private int resourceID;
        public ModeAdapter(Context ctx, int resourceId, List<JSONObject> list) {
            super(ctx,resourceId,list);
            resourceID = resourceId;
        }

        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

            JSONObject mode = getItem(position);
            ViewHolder holder = null;
            View cell;
            if (convertView == null) {
                cell = LayoutInflater.from(getContext()).inflate(resourceID,null);
                holder = new ViewHolder();
                holder.mode = (TextView) cell.findViewById(R.id.mode_name_tv);
                cell.setTag(holder);
            } else  {
                cell = convertView;
                holder = (ViewHolder)cell.getTag();
            }

            try {

                String name = mode.getString("name").toString();
                String desc = mode.optString("description",null).toString();
//                desc = "dfhajkdhfadfjagdjfgajkdgajdgjafgdsjgajkdfakdadaljlflaalsallsadf44566";
                if (name != null && name.length() > 0 && desc != null && desc.length() > 0) {
                    String str = name + " -- " + desc;
                    Spannable span = new SpannableString(str);
                    /**
                     *
                     * Spanned.SPAN_EXCLUSIVE_EXCLUSIVE --- 不包含两端start和end所在的端点         (a,b)
                     * Spanned.SPAN_EXCLUSIVE_INCLUSIVE --- 不包含端start，但包含end所在的端点     (a,b]
                     * Spanned.SPAN_INCLUSIVE_EXCLUSIVE --- 包含两端start，但不包含end所在的端点   [a,b)
                     * Spanned.SPAN_INCLUSIVE_INCLUSIVE--- 包含两端start和end所在的端点           [a,b]
                     * */
                    span.setSpan(new AbsoluteSizeSpan(17,true), name.length() + 1, str.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    span.setSpan(new ForegroundColorSpan(Color.RED),name.length() + 1,str.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    span.setSpan(new AbsoluteSizeSpan(20,true), 0, name.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    span.setSpan(new ForegroundColorSpan(Color.BLACK),0,name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    holder.mode.setText(span);
                } else {
                    holder.mode.setText(name);
                }


                int enable = mode.getInt("enable");

                if (enable == 0) {
                    cell.setBackgroundColor(getResources().getColor(R.color.dark_gray));
                } else  {
                    cell.setBackgroundColor(getResources().getColor(R.color.clear_color));
                }
                return cell;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        class ViewHolder {
            TextView mode;
        }
    }
}
