package com.xplora.xpsettings.Data;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.xplora.xpsettings.Model.ApnModel;
import com.xplora.xpsettings.Utils.Macros;

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

public class ApnManager {
    public static String TAG = "losion / xpsettings :" + "ApnManager";

    public static Uri APN_URI = Uri.parse("content://telephony/carriers");
    public static Uri CURRENT_APN_URI = Uri.parse("content://telephony/carriers/preferapn");

    @SuppressLint("Range")
    public static List<ApnModel> getAPNList(Context context, List<ApnModel> modelList){
        Log.d(TAG, "getAPNList: " + modelList.size());
        List<ApnModel> list = new ArrayList<ApnModel>();
        for (ApnModel model: modelList) {
            ApnModel apnModel = getAPNListOne(context, model._id, model.apn_id);
            if (apnModel != null) {
                list.add(apnModel);
            }
        }
        return list;
    }

    public static ApnModel getAPNListOne(Context context, String _id, String apn_id){
        List<ApnModel> list = new ArrayList<ApnModel>();
        ContentResolver resolver = context.getContentResolver();

        Cursor cr = resolver.query(APN_URI, null,  "_id =?", new String[]{ _id } , null);
        while(cr!=null && cr.moveToNext()){
            ApnModel a = new ApnModel();
            a._id = getCursorColumnValue(cr,"_id");
            a.name = getCursorColumnValue(cr,"name");
            a.apn_name = getCursorColumnValue(cr,"apn");
            a.user_name = getCursorColumnValue(cr,"user");
            a.password = getCursorColumnValue(cr,"password");
            a.mcc = getCursorColumnValue(cr,"mcc");
            a.mnc = getCursorColumnValue(cr,"mnc");
            a.proxy = getCursorColumnValue(cr,"proxy");
            a.port = getCursorColumnValue(cr,"port");
            a.server = getCursorColumnValue(cr,"server");
            a.mmsc = getCursorColumnValue(cr,"mmsc");
            a.mmsproxy = getCursorColumnValue(cr,"mmsproxy");
            a.mmsport = getCursorColumnValue(cr,"mmsport");
            a.auth_type = getCursorColumnValue(cr,"authtype");
            a.apn_type = getCursorColumnValue(cr,"type");
            a.apn_protocol = getCursorColumnValue(cr,"protocol");
            a.apn_roaming_protocol = getCursorColumnValue(cr,"roaming_protocol");
            a.bearer = getCursorColumnValue(cr,"bearer");
            a.mvno_type = getCursorColumnValue(cr,"mvno_type");
            a.mvno_match_data = getCursorColumnValue(cr,"mvno_match_data");
            a.apn_id = apn_id;
            cr.close();
            return a;
        }
        if(cr!=null)
            cr.close();
        return null;
    }

    public static int insertAPN(Context context, ApnModel apnModel) {
        String NUMERIC = getSIMInfo(context);
        if (NUMERIC == null)
            return -1;
        ContentValues values = getContentValues(apnModel, NUMERIC);
        ContentResolver resolver = context.getContentResolver();
        Uri newRow = resolver.insert(APN_URI, values);
        if (newRow == null)
            return -1;

        long value = ContentUris.parseId(newRow);
        Log.d(TAG, "insertAPN: row: " + value);
        int _id = Integer.parseInt(String.valueOf(value));

        setCurrentAPN(context, _id);
        return _id;
    }

    public static void editAPN(Context context, ApnModel apnModel) {
        Log.d(TAG, "editAPN: " + apnModel._id);
        if (apnModel._id == null || apnModel._id.isEmpty())
            return;
        String NUMERIC = getSIMInfo(context);
        if (NUMERIC == null)
            return;
        ContentValues values = getContentValues(apnModel, NUMERIC);
        ContentResolver resolver = context.getContentResolver();
        int value = resolver.update(APN_URI, values, "_id" + "=?", new String[] { apnModel._id });
        Log.d(TAG, "editAPN result:" + value);

        setCurrentAPN(context, Integer.parseInt(apnModel._id));
    }

    public static void deleteAPN(Context context, ApnModel apnModel) {
        Log.d(TAG, "deleteAPN: " + apnModel._id);
        if (apnModel._id == null || apnModel._id.isEmpty())
            return;
        ContentResolver resolver = context.getContentResolver();
        int returnValue = resolver.delete(APN_URI,  "_id" + "=?", new String[] { apnModel._id });
    }

    // 设置接入点
    public static void setCurrentAPN(Context context, int _id) {
        ContentResolver resolver = context.getContentResolver();
        ContentValues values = new ContentValues();
        values.put("apn_id", _id);
        int returnValue = resolver.update(CURRENT_APN_URI, values, null, null);
        Log.d(TAG, "setCurrentAPN: " + returnValue);
    }

    public static ApnModel getCurrentAPN(Context context){
        if (Macros.DEBUG) {
            ApnModel a = new ApnModel();
            a.name = "name";
            a.apn_name = "apn name";
            a.user_name = "current";
            a.password = "current";
            a.mcc = "current";
            a.mnc = "current";
            a.isCurrentApn = true;
            return a;
        } else {
            ContentResolver resolver = context.getContentResolver();
            Cursor cr = resolver.query(CURRENT_APN_URI, null, null, null, null);
            if (cr == null)
                return null;
            if (!cr.moveToFirst()) {
                cr.close();
                return null;
            }
            Log.d(TAG, "getCurrentAPN: ok");
            ApnModel a = new ApnModel();
            a._id = getCursorColumnValue(cr,"_id");
            a.name = getCursorColumnValue(cr,"name");
            a.apn_name = getCursorColumnValue(cr,"apn");
            a.user_name = getCursorColumnValue(cr,"user");
            a.password = getCursorColumnValue(cr,"password");
            a.mcc = getCursorColumnValue(cr,"mcc");
            a.mnc = getCursorColumnValue(cr,"mnc");
            a.proxy = getCursorColumnValue(cr,"proxy");
            a.port = getCursorColumnValue(cr,"port");
            a.server = getCursorColumnValue(cr,"server");
            a.mmsc = getCursorColumnValue(cr,"mmsc");
            a.mmsproxy = getCursorColumnValue(cr,"mmsproxy");
            a.mmsport = getCursorColumnValue(cr,"mmsport");
            a.auth_type = getCursorColumnValue(cr,"authtype");
            a.apn_type = getCursorColumnValue(cr,"type");
            a.apn_protocol = getCursorColumnValue(cr,"protocol");
            a.apn_roaming_protocol = getCursorColumnValue(cr,"roaming_protocol");
            a.bearer = getCursorColumnValue(cr,"bearer");
            a.mvno_type = getCursorColumnValue(cr,"mvno_type");
            a.mvno_match_data = getCursorColumnValue(cr,"mvno_match_data");
            a.isCurrentApn = true;
            cr.close();
            return a;
        }
    }

    public static ContentValues getContentValues(ApnModel apnModel, String NUMERIC) {
        ContentValues values = new ContentValues();
        values.put("name", apnModel.name); //apn中文描述
        values.put("apn", apnModel.apn_name); //apn名称
        values.put("user", apnModel.user_name); //用户名
        values.put("password", apnModel.password); //密码
        values.put("mcc", apnModel.mcc);
        values.put("mnc", apnModel.mnc);
        values.put("numeric", NUMERIC);
        values.put("proxy", apnModel.proxy); //代理
        values.put("port", apnModel.port); //端口
        values.put("server", apnModel.server); //服务器
        values.put("mmsc", apnModel.mmsc); //MMSC
        values.put("mmsproxy", apnModel.mmsproxy); //彩信代理
        values.put("mmsport", apnModel.mmsport); //彩信端口
        values.put("authtype", apnModel.auth_type);
        values.put("type",  apnModel.apn_type.equals("") ? "default" : apnModel.apn_type); //apn类型
        values.put("protocol", apnModel.apn_protocol);
        values.put("roaming_protocol", apnModel.apn_roaming_protocol);
        values.put("bearer", apnModel.bearer);
        values.put("mvno_type", apnModel.mvno_type);
        values.put("mvno_match_data", apnModel.mvno_match_data);
        return values;
    }

    public static String getSIMInfo(Context context) {
        TelephonyManager iPhoneManager = (TelephonyManager)context
                .getSystemService(Context.TELEPHONY_SERVICE);
        return iPhoneManager.getSimOperator();
    }

    public static String getCursorColumnValue(Cursor cr, String key) {
        int index = cr.getColumnIndex(key);
        if (index < 0)
            return "";
        return cr.getString(index);
    }
}