package com.agilex.healthcare.schedulingmanager.datalayer;

import com.agilex.healthcare.schedulingmanager.domain.SchedulingSpecialties;
import com.agilex.healthcare.schedulingmanager.translator.SpecialtyTranslator;
import agilex.commons.helper.MongoHelper;
import agilex.commons.helper.PropertyHelper;
import com.mongodb.*;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import java.net.UnknownHostException;

public class SpecialtyDataLayerMongo implements SpecialtyDataLayer {

    private final org.apache.commons.logging.Log LOGGER = org.apache.commons.logging.LogFactory.getLog(SpecialtyDataLayerMongo.class);

    private DBCollection collection;
    private DB db;
    private MongoClient mongoClient;
    private String facilityCodeKey = "facility";
    private String nameKey = "name";
    private SpecialtyTranslator specialtyTranslator = new SpecialtyTranslator();

    @Resource
    PropertyHelper propertyHelper;


    /*public SpecialtyDataLayerMongo(){
        try {
            mongoClient = new MongoClient(MongoHelper.getMongoUri(propertyHelper));
            //mongoClient = new MongoClient();
            db = mongoClient.getDB("facility-definition");
            collection = db.getCollection("specialtyServiceToClinic");
        } catch (UnknownHostException e) {
            LOGGER.error("Unable to connect to Mongo DB - Unknown Host Exception", e);
            throw new RuntimeException("Unable to connect to Mongo DB - Unknown Host Exception", e);
        } catch (MongoException e) {
            LOGGER.error("Unable to connect to Mongo DB - Mongo Exception", e);
            throw new RuntimeException("Unable to connect to Mongo DB - Mongo Exception", e);
        }
    }*/

    @PostConstruct
    public void init(){
    	try {
            mongoClient = new MongoClient(MongoHelper.getMongoUri(propertyHelper));
            db = mongoClient.getDB("facility-definition");
            collection = db.getCollection("specialtyServiceToClinic");
        } catch (UnknownHostException e) {
            LOGGER.error("Unable to connect to Mongo DB - Unknown Host Exception", e);
            throw new RuntimeException("Unable to connect to Mongo DB - Unknown Host Exception", e);
        } catch (MongoException e) {
            LOGGER.error("Unable to connect to Mongo DB - Mongo Exception", e);
            throw new RuntimeException("Unable to connect to Mongo DB - Mongo Exception", e);
        }
    }

    public SchedulingSpecialties fetchSpecialties(String facilityCode) {

		BasicDBObject query = new BasicDBObject(facilityCodeKey, facilityCode);
		DBCursor iterator = collection.find(query).sort(new BasicDBObject(nameKey, 1));

        SchedulingSpecialties schedulingSpecialties = new SchedulingSpecialties();
        while(iterator.hasNext()) {
			DBObject specialty = iterator.next();
			schedulingSpecialties.add(specialtyTranslator.translate(specialty));
		}

		return schedulingSpecialties;
    }
}
