package com.miya.weighing;

import android.content.Context;

/**
 * 标准称重接口的实现基类
 *
 * @author pupu
 * @time 2018/10/19
 */
public class BaseWeighing implements Weighing {

    /**
     * 保存调用者上下文
     */
    Context context;

    /**
     * 重量回调
     */
    WeighingCallback weighingCallback;

    /**
     * 当前称台重量，单位g
     */
    int curWeight;

    /**
     * 皮重
     */
    int tare;

    /**
     * 硬件名称
     */
    String name;


    @Override
    public void setWeighingName(String name) {
        this.name = name;
    }

    @Override
    public String getWeighingName() {
        return name;
    }

    @Override
    public boolean init(Context context) {
        this.context = context;
        return false;
    }

    @Override
    public boolean release() {
        return false;
    }

    @Override
    public int getWeight() {
        return curWeight;
    }

    @Override
    public boolean resetZero() {
        return false;
    }

    @Override
    public boolean setTare(int tare) {
        this.tare = tare;
        return true;
    }

    @Override
    public boolean setGravity(double gravity) {
        return false;
    }

    @Override
    public boolean markWeight(int weight) {
        return false;
    }

    @Override
    public int getWeightWithOutTare() {
        return 0;
    }

    @Override
    public void setWeighingCallback(WeighingCallback weighingCallback) {
        this.weighingCallback = weighingCallback;
    }

    /**
     * 将保留3位小数的重量转换位去掉小数点的整形重量，方便计算，避免float等的精度损失
     *
     * @param kg 单位为kg的重量
     * @return 单位为g的重量，返回去掉小数点的整形
     */
    public int parseKg2g(String kg) {
        if (kg.contains(".")) {
            String result = "";
            int index = kg.indexOf(".");
            String tmp1 = kg.substring(0, index);
            String tmp2 = kg.substring(index + 1, kg.length());
            if (tmp2.length() == 0) {
                tmp2 = "000";
            } else if (tmp2.length() == 1) {
                tmp2 = tmp2 + "00";
            } else if (tmp2.length() == 2) {
                tmp2 = tmp2 + "0";
            } else if (tmp2.length() > 3) {
                tmp2 = tmp2.substring(0, 3);
            }
            result = tmp1 + tmp2;
            //担心数据库中有非数字的值，最后考虑还是catch下；同时防止pos出现负数重量的奇葩傻逼情况，最后考虑还是绝对值abs一下
            int resultInt = 0;
            try {
                resultInt = Integer.parseInt(result);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return resultInt;
        } else {
            //担心数据库中有非数字的值，最后考虑还是catch下
            int resultInt = 0;
            try {
                resultInt = Integer.parseInt(kg + "000");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return resultInt;
        }
    }

    /**
     * 将单位为g的重量转换为kg，保留3为小数
     *
     * @param g
     * @return
     */
    public double parseg2kg(int g) {
        return g / 1000.000d;
    }
}
