package org.bdware.sc.blockdb;

import okhttp3.*;
import org.bdware.sc.commParser.BDLedger.Transaction;
import org.bdware.sc.util.JsonUtil;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ElasticDBUtil implements DBRepository {
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    public OkHttpClient client = new OkHttpClient();
    public List<Transaction> transactions = new ArrayList<>();
    public int bulk = 10000;

    @Override
    public String Get(Map<String, Object> condition) {
        // TODO Auto-generated method stub
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> map1 = new HashMap<>();
        Map<String, String> map2 = new HashMap<>();
        map2.put("data", condition.get("data") + "*");
        map1.put("wildcard", map2);
        map.put("query", map1);
        String json = JsonUtil.toJson(map);
        RequestBody requestbody = FormBody.create(json, JSON);
        Request request = new Request.Builder().url("http://127.0.0.1:9200/transaction/_doc/_search").post(requestbody).build();
        try {
            Response resp = client.newCall(request).execute();
            System.out.print(resp.body().string());
            resp.body().close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return json;
    }

    @Override
    public boolean Put(Transaction trans) {
        // TODO Auto-generated method stub
        transactions.add(trans);
        if (transactions.size() == bulk) {
            StringBuilder sb = new StringBuilder();
            try {
                for (int i = 0; i < bulk; i++) {
                    sb
                            .append("{\"index\":{}}\n{\"data\":\"")
                            .append(new String(transactions.get(i).data, StandardCharsets.UTF_8))
                            .append("\",")
                            .append("\"hash\":")
                            .append("\"")
                            .append(new String(transactions.get(i).hash, StandardCharsets.UTF_8))
                            .append("\"")
                            .append("}")
                            .append("\n");
                }
                //System.out.println(sb.toString());
                RequestBody requestbody = FormBody.create(sb.toString(), JSON);
                Request request = new Request.Builder().url("http://127.0.0.1:9200/transaction/_doc/_bulk").post(requestbody).build();
                Response res1 = client.newCall(request).execute();
                boolean res = res1.isSuccessful();
                res1.body().close();
                System.out.println(res);
                transactions.clear();
                return res;
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return false;
    }

    @Override
    public boolean Delete(String hash) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean Create_DB() {
        // TODO Auto-generated method stub
        RequestBody body = RequestBody.create("", JSON);
        Request request = new Request.Builder().url("http://127.0.0.1:9200/transaction/").put(body).build();
        try {
            Response response = client.newCall(request).execute();
            boolean res = response.isSuccessful();
            response.body().close();
            return res;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean Open_DB() {
        // TODO Auto-generated method stub
        return false;
    }
}
