# tr_mongo_search.py    chromatic universe  2018   william k. johnson


import datetime
from datetime import datetime , timedelta
from io import StringIO
import sys
import time
import json
import os
import pprint
import sys
from time import sleep , strptime
import tornado.websocket
import tornado.httpserver
import collections
import tornado

from tornado.queues import Queue
from tornado.ioloop import PeriodicCallback
from tornado.locks import Semaphore
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.escape import json_decode, json_encode
from tornado import gen
from tornado import web
from bson import SON , ObjectId
from bson import json_util
from io import StringIO
#chilkat mime
import chilkat

#motor
import motor.motor_tornado

cci_mongo = motor.motor_tornado.MotorClient( 'mongodb://localhost/?replicaSet=rs0' )
mongo_db = cci_mongo.imap2017
from cci_mta_trinity.streams.tr_mongo_rest import _logger
from cci_mta_trinity.streams.tr_mime import stage_one_mime_container


# -------------------------------------------------------------------------------------------------
@tornado.gen.coroutine
def chomp( source) :
                    """

                    :param source:
                    :return:
                    """

                    return source[1:-1]



# -------------------------------------------------------------------------------------------------
@tornado.gen.coroutine
def imap_internal_to_iso_date( source ) :
                    """

                    :param source:
                    :return iso date:
                    """

                    s = source
                    # split
                    ls = s.split( '-' )
                    # month chars to month sequence
                    ls[1] = strptime( ls[1] , '%b').tm_mon
                    # leading zero
                    ls[1] = "%02d" % ls[1]

                    # clumsy mongodb implementation : requires date range to specify
                    # exact day , thus this mishegas
                    obj = datetime.strptime( source , '%d-%b-%Y' )
                    next_obj = obj + timedelta( days=1 )
                    new_day = next_obj.strftime( '%d-%m-%Y' )
                    nls = new_day.split( '-' )

                    # format iso , day after iso
                    return obj , next_obj





# -------------------------------------------------------------------------------------------------
@tornado.gen.coroutine
def handle_message_ids( store_moniker , scope , buckets )  :
                    """

                    :param store_moniker:
                    :param scope:
                    :param buckets:
                    :return:
                    """

                    _logger.info( '...handle_message_ids...' )

                    bucket = None