#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division,print_function
import sys,os
import pandas as pd
import pymongo
from pymongo import MongoClient
import random,operator
from collections import OrderedDict
from bson.son import SON
from bson.codec_options import CodecOptions

def extract_pmidDoc_fromMedline(pmid,fromDBCollection,toDBCollection):
    abstract_raw_doc = fromDBCollection.find_one({"docId":pmid})
    if abstract_raw_doc:
        insert_to_DB("docId",pmid,abstract_raw_doc,toDBCollection)


def insert_to_DB(key,value,doc,db):
    if not db.find_one({key:value}):
        db.insert_one(SON(doc))
        #print("=:> inserted to ",db_name_to,":",toCollectionName)
        #print("Inserted text for ",value)

def run_create_text_table(pmidFile,fromDBCollection,toDBCollection):
    pmidList = pd.read_csv(pmidFile,header=None).iloc[:,0].tolist() # : for all rows, 0 for col1
    # print(pmidList)
    for index,pmid in enumerate(pmidList):
        #print(index,":",pmid)
        extract_pmidDoc_fromMedline(str(pmid),fromDBCollection,toDBCollection)
        # break



if __name__ == "__main__":
    pmidFile = sys.argv[1]
    dbF = sys.argv[2]
    dbT = sys.argv[3]
    colF = sys.argv[4]
    colT = sys.argv[5]


    #--- create database instances---
    # Environment variables
    mongodb_host = os.environ.get("MONGODB_HOST","0.0.0.0") # change to biotm2.cis.udel.edu before dockerizing
    mongodb_port = os.environ.get("MONGODB_PORT","27017")
    db_name_from = os.environ.get("DBNAME_FROM",dbF) # change database name for your own dbName
    db_name_to = os.environ.get("DBNAME_TO",dbT) # change database name for your own dbName

    fromCollectionName = os.environ.get("COLLECTION_FROM",colF)
    toCollectionName = os.environ.get("COLLECTION_TO",colT)
    # Database URI
    MONGODB_URI = 'mongodb://'+mongodb_host+':'+mongodb_port+'/'

    # Database object
    client = MongoClient(MONGODB_URI)
    opts = CodecOptions(document_class=SON)

    # Database
    dbNameFrom = client[db_name_from] # medline
    dbNameTo = client[db_name_to] # New DB: glygen

    # Collection
    fromDBCollection = dbNameFrom[fromCollectionName].with_options(codec_options=opts)
    toDBCollection = dbNameTo[toCollectionName].with_options(codec_options=opts)


    run_create_text_table(pmidFile,fromDBCollection,toDBCollection)
