package com.xplora.xpsettings.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.xplora.xpsettings.Adapter.BaseListAdapter;
import com.xplora.xpsettings.Data.ApnManager;
import com.xplora.xpsettings.Data.DataManager;
import com.xplora.xpsettings.Data.DatabaseHelper;
import com.xplora.xpsettings.Model.ApnModel;
import com.xplora.xpsettings.Model.BaseModel;
import com.xplora.xpsettings.R;
import com.xplora.xpsettings.Utils.Constant;
import com.xplora.xpsettings.Utils.ResUtils;

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


public class ApnListActivity extends BaseActionActivity {
    List<ApnModel> mApnList = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate: ");
        setContentView(R.layout.activity_list);
        moveApn();
        initApn();
        initData();
        initView();
    }

    private void moveApn() {
        List<ApnModel> apnModelList = DataManager.getApnListFromSP();
        Log.d(TAG, "moveApn: size: " + apnModelList.size());
        if (apnModelList.size() <= 0)
            return;
        for (ApnModel model: apnModelList) {
            DatabaseHelper.insertAPN(this, model.apn_id);
        }
        DataManager.setApnListToSP(new ArrayList<>());
    }

    private void initApn() {
        ApnModel currentApn = ApnManager.getCurrentAPN(this);
        if (currentApn != null) {
            Log.d(TAG, "initApn currentApn: " + currentApn.name + " _id:" +currentApn._id + " mcc:" + currentApn.mcc + " mnc:" + currentApn.mnc);
            currentApn.isCurrentApn = true;
            mApnList.add(currentApn);
        }

        //排除当前正在使用的apn
        List<ApnModel> modelList = DatabaseHelper.getCustomApnList(this);
        List<ApnModel> apnModelList = ApnManager.getAPNList(this, modelList);
        Log.d(TAG, "initApn: customApn size: " + apnModelList.size());
        for (ApnModel model: apnModelList) {
            Log.d(TAG, "initApn customApn: " + model.name + " apn_id:" + model.apn_id + " _id:" + model._id + " mcc:" + model.mcc + " mnc:" + model.mnc);
            model.isCurrentApn = false;
            if (currentApn == null || currentApn._id.isEmpty()) {
                mApnList.add(model);
            } else {
                if (!model._id.equals(currentApn._id)) {
                    mApnList.add(model);
                }
            }
        }
    }

    private void initData() {
        for (int i = 0; i < mApnList.size(); i++) {
            addBaseMode(mApnList.get(i));
        }
        //底部加按钮
        if (mApnList.size() > 0) {
            BaseModel model = new BaseModel();
            model.cellType = Constant.CellType.APN_ADD;
            mDataList.add(model);
        }
    }

    private void addBaseMode(ApnModel apnModel) {
        String[] stringList = ResUtils.getStringArray("apn_title_array_", 19);
        String mcc = stringList[1] + ": " + (apnModel.mcc.isEmpty() ? getString(R.string.not_set) : apnModel.mcc);
        String mnc = stringList[2] + ": " + (apnModel.mnc.isEmpty() ? getString(R.string.not_set) : apnModel.mnc);
        BaseModel model = new BaseModel();
        model.title = apnModel.name.trim().isEmpty() ? apnModel.apn_name.trim() : apnModel.name.trim();;
        model.titileColor = apnModel.isCurrentApn?  R.color.xp_green : R.color.white;
        model.isOn = apnModel.isCurrentApn;
        model.subTitle = mcc + "    " + mnc;
        model.cellType = Constant.CellType.TITLE_APN;
        mDataList.add(model);
    }

    private void initView() {
        ListView listView = findViewById(R.id.activity_listview);
        View emptyView = findViewById(R.id.empty_view);

        listView.setDividerHeight(0);
        listView.setVisibility(mApnList.size() == 0 ? View.GONE : View.VISIBLE);
        emptyView.setVisibility(mApnList.size() == 0 ? View.VISIBLE : View.GONE);

        initEmptyView();
        initList(listView);
    }

    private void initEmptyView() {
        TextView textView = findViewById(R.id.empty_text);
        textView.setText(R.string.apn_hint);

        Button button = findViewById(R.id.empty_button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clickAddButton();
            }
        });
    }

    private void initList(ListView listView) {
        mAdapter = new BaseListAdapter(this, 0, mDataList, mHandler);
        listView.setAdapter(mAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //最后一个是空view
                if (position >= mDataList.size()-1)
                    return;
                Log.d(TAG, "onItemClick: " + position);
                Intent intent = new Intent(ApnListActivity.this, ApnEditActivity.class);
                intent.putExtra(Constant.INTENT_VIEW_VALUE, 0);
                intent.putExtra(Constant.INTENT_RESULT_VALUE, mApnList.get(position));
                startActivityForResult(intent, 0);
            }
        });

        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                //最后一个是空view
                if (position >= mDataList.size()-1)
                    return true;
                ApnModel apnModel = mApnList.get(position);
                boolean isCustom = DataManager.isCustomApn(apnModel);
                if (!isCustom)
                    return true;
                Intent intent = new Intent(ApnListActivity.this, ApnDeleteActivity.class);
                intent.putExtra(Constant.INTENT_RESULT_VALUE, mApnList.get(position));
                startActivityForResult(intent, 0);
                return true;
            }
        });
    }

    public void clickAddButton() {
        Intent intent = new Intent(ApnListActivity.this, ApnEditActivity.class);
        intent.putExtra(Constant.INTENT_VIEW_VALUE, 1);
        startActivityForResult(intent, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null)
            return;
        if (data.getAction().equals(Constant.INTENT_RESULT_ACTION)) {
            int type = data.getIntExtra(Constant.INTENT_VIEW_VALUE, 0);
            ApnModel apnModel = (ApnModel)data.getSerializableExtra(Constant.INTENT_RESULT_VALUE);
            if (type == 1) {
                insertApn(apnModel);
            } else {
                updateAPN(apnModel);
            }
        } else if (data.getAction().equals(Constant.INTENT_RESULT_ACTION_REMOVE)) {
            ApnModel model = (ApnModel)data.getSerializableExtra(Constant.INTENT_RESULT_VALUE);
            deleteApn(model);
        }
    }

    void insertApn(ApnModel apnModel) {
        int _id = ApnManager.insertAPN(getApplicationContext(), apnModel);
        if (_id < 0)
            return;
        apnModel._id = String.valueOf(_id);
        DatabaseHelper.insertAPN(this, apnModel._id);
        reloadView();
    }

    void updateAPN(ApnModel apnModel) {
        ApnManager.editAPN(getApplicationContext(), apnModel);
        DatabaseHelper.updateAPN(this, apnModel);
        reloadView();
    }

    void deleteApn(ApnModel model) {
        ApnManager.deleteAPN(getApplicationContext(), model);
        DatabaseHelper.deleteAPN(this, model);
        reloadView();
    }

    void reloadView() {
        mApnList.clear();
        mDataList.clear();
        initApn();
        initData();
        initView();
        mAdapter.setBaseObjects(mDataList);
        mAdapter.notifyDataSetInvalidated();
    }

    Handler mHandler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == Constant.MSG_SURE_CLICK) {
                clickAddButton();
            } else if (msg.what == Constant.MSG_APN_CLICK) {
                clickAddButton();
            }
        }
    };
}