package com.yihu.hos.common.util;

import com.mongodb.client.MongoDatabase;
import com.yihu.ehr.dbhelper.mongodb.MongodbFactory;
import com.yihu.ehr.dbhelper.mongodb.MongodbHelper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.bson.Document;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/10/13.
 */
public class MongodbUtil extends MongodbHelper {

    private MongoDatabase db;
    public String errorMessage;

    public MongodbUtil() {
        this.db = MongodbFactory.getDB();
    }

    public MongodbUtil(String dbName) {
        this.db = MongodbFactory.getDB(dbName);
    }

    public synchronized boolean insert(String name, Document data) {
        try {
            this.db.getCollection(name).insertOne(data);
            return true;
        } catch (Exception var4) {
            var4.printStackTrace();
            this.errorMessage = var4.getMessage();
            return false;
        }
    }

    public synchronized boolean insertArray(String name, List<JSONObject> data) {
        try {
            this.db.getCollection(name).insertOne(Document.parse(data.toString()));
            return true;
        } catch (Exception var4) {
            var4.printStackTrace();
            this.errorMessage = var4.getMessage();
            return false;
        }
    }

    public synchronized boolean insertList(String name,JSONArray dataList) {
        try {
            ArrayList e = new ArrayList();
            Iterator var4 = dataList.iterator();

            while(var4.hasNext()) {
                JSONObject json = (JSONObject)var4.next();
                Document doc = Document.parse(json.toString());
                e.add(doc);
            }

            this.db.getCollection(name).insertMany(e);
            return true;
        } catch (Exception var7) {
            var7.printStackTrace();
            this.errorMessage = var7.getMessage();
            return false;
        }
    }


}
