package com.cerveza.togglefunction;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.util.Log;

import com.cerveza.togglefunction.api.EMessageType;
import com.cerveza.togglefunction.api.MyBatteryInfo;
import com.cerveza.togglefunction.serializeutil.SerializeUtils;

import java.io.IOException;

/**
 * Created by cerveza on 04.03.2017.
 */

public class BatteryStatusReceiver extends BroadcastReceiver {

    public static final IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);

    @Override
    public void onReceive(Context context, Intent intent) {
        MyBatteryInfo myBatteryInfo = new MyBatteryInfo(getCapacity(intent),getStatus(intent),
                getHealth(intent),getPowerSource(intent));

        sendMessage(context, EMessageType.OVERVIEW_UPDATE_BATTERY.getPath(),serialize(myBatteryInfo));

    }

    private int getCapacity(Intent intent){
        int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        return  level;// / scale;
    }

    private int getHealth(Intent intent){
        int healt = intent.getIntExtra(BatteryManager.EXTRA_HEALTH,-1);
        return  healt;
    }
    private int getStatus(Intent intent){
       return  intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
    }
    private int getPowerSource(Intent intent){
        int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        return  chargePlug;
    }

    public void sendMessage(Context context, String path, byte[] data){
        Intent intent = new Intent(context,MessageSendService.class).setAction("SEND_MESSAGE").
                putExtra("MESSAGE_PATH",path).putExtra("BYTES",data);
        context.startService(intent);
    }

    public byte[] serialize (Object object){
        byte[] bytes;
        try {
            bytes = SerializeUtils.convertToBytes(object);
            return bytes;
        } catch (IOException e) {
            Log.e(getClass().getName(),"IO exeption during converting from object to bytes",e);
        }
        return null;
    }
}
