package com.vsu.fcounter.smilepay;

import androidx.annotation.NonNull;

import com.alipay.zoloz.smile2pay.service.Zoloz;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;

import java.util.HashMap;
import java.util.Map;

public class SmilepayModule extends ReactContextBaseJavaModule {

    private Zoloz zoloz;
    private ReactContext reactContext;

    public SmilepayModule(ReactContext reactContext) {
        this.reactContext = reactContext;
    }

    @NonNull
    @Override
    public String getName() {
        return "Smilepay";
    }

    @ReactMethod
    void init(ReadableMap params, Promise promise) {
        zoloz = com.alipay.zoloz.smile2pay.service.Zoloz.getInstance(reactContext.getApplicationContext());
        zoloz.zolozGetMetaInfo(params.toHashMap(), map -> {
            if (map == null) {
                promise.resolve(false);
                return;
            }
            String code = (String)map.get("code");
            String metaInfo = (String)map.get("metainfo");
            WritableMap data = Arguments.createMap();
            data.putString("code", code);
            data.putString("metaInfo", metaInfo);
            promise.resolve(data);
        });
    }

    @ReactMethod
    void verify(ReadableMap params, Promise promise) {
        String zimId = params.getString("zimId");
        String protocal = params.getString("zimInitClientData");
        HashMap<String, String> req = new HashMap<>();
        if (protocal != null) req.put("zim.init.resp", protocal);
        zoloz.zolozVerify(zimId, req, map -> {
            if (map == null) {
                promise.resolve(false);
                return;
            }
            String code = (String)map.get( "code" );
            String msg = (String)map.get( "msg" );
            WritableMap data = Arguments.createMap();
            data.putString("code", code);
            data.putString("msg", msg);
            if ("1000".equals(code)) {
                String fToken = (String)map.get( "ftoken" );
                String subCode = (String)map.get( "subCode" );
                String uid = (String)map.get( "alipayUid" );
                String result = (String)map.get( "result" );
                data.putString("fToken", fToken);
                data.putString("subCode", subCode);
                data.putString("uid", uid);
                data.putString("result", result);
            }
            promise.resolve(data);
        });
    }

}
