package com.czg.cashier_reserve.call;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.provider.CallLog;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.czg.cashier_reserve.ContextHolder;
import com.czg.cashier_reserve.channel.EventChannelManager;

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

import java.text.SimpleDateFormat;
import java.util.Date;

import io.flutter.Log;

public class CallManager {
	private static final String[] columns = {CallLog.Calls.CACHED_NAME// 通话记录的联系人
			, CallLog.Calls.NUMBER// 通话记录的电话号码
			, CallLog.Calls.DATE// 通话记录的日期
			, CallLog.Calls.DURATION// 通话时长
			, CallLog.Calls.TYPE};// 通话类型}

	public static void loadCallLog() {
		Context mainActivityContext = ContextHolder.getInstance().getContext();
		Log.i("CallManager","loadCallLog -- " + mainActivityContext);
		Cursor cursor = mainActivityContext.getContentResolver().query(CallLog.Calls.CONTENT_URI,
				columns, null, null, null);

		JSONArray callLogArray = new JSONArray();

		Log.i("CallManager","cursor count:" + cursor.getCount());
		while (cursor.moveToNext()) {
			@SuppressLint("Range") String name = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));  //姓名
			@SuppressLint("Range") String number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));  //号码
			@SuppressLint("Range") long dateLong = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE)); //获取通话日期
			@SuppressLint("SimpleDateFormat") String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(dateLong));
			@SuppressLint("SimpleDateFormat") String time = new SimpleDateFormat("HH:mm").format(new Date(dateLong));
			@SuppressLint("Range") int duration = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.DURATION));//获取通话时长，值为多少秒
			@SuppressLint("Range") int type = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE)); //获取通话类型：1.呼入2.呼出3.未接
//			@SuppressLint("SimpleDateFormat") String dayCurrent = new SimpleDateFormat("dd").format(new Date());
//			@SuppressLint("SimpleDateFormat") String dayRecord = new SimpleDateFormat("dd").format(new Date(dateLong));

			JSONObject callLog = new JSONObject();
			try {
				callLog.put("name", name);
				callLog.put("number", number);
				callLog.put("date", date);
				callLog.put("duration", duration);
				callLog.put("type", type);
				callLog.put("time", time);
			} catch (Exception e) {
				e.printStackTrace();
			}

			callLogArray.put(callLog);
		}

		Log.i("CallManager", "callLogArray: " + callLogArray);

		Intent broad = new Intent(EventChannelManager.Action.GET_CALL_LOG_FINISH);
		broad.putExtra("callLog", callLogArray.toString());
		mainActivityContext.sendBroadcast(broad);
		Log.i("CallManager", "send broadcast");
	}
}
