#!/usr/bin/env python
__doc__ = """
(c) 2018 - 2021 data-transport
steve@the-phi.com, The Phi Technology LLC
https://dev.the-phi.com/git/steve/data-transport.git

This program performs ETL between 9 supported data sources  : Couchdb, Mongodb, Mysql, Mariadb, PostgreSQL, Netezza,Redshift, Sqlite, File
LICENSE (MIT)
Copyright 2016-2020, The Phi Technology LLC

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


Usage :
	transport --config <path-to-file.json> --procs <number-procs>
@TODO: Create tables if they don't exist for relational databases
example of configuration :

1. Move data from a folder to a data-store
	transport [--folder <path> ] --config <config.json>	 #-- assuming the configuration doesn't have folder 
	transport --folder <path> --provider <postgresql|mongo|sqlite> --<database|db> <name> --table|doc <document_name>
In this case the configuration should look like :
	{folder:..., target:{}}
2. Move data from one source to another
	transport --config <file.json>
	{source:{..},target:{..}} or [{source:{..},target:{..}},{source:{..},target:{..}}]
	

"""
import pandas as pd
import numpy as np
import json 
import sys
import transport
import time
from multiprocessing import Process
SYS_ARGS = {}
if len(sys.argv) > 1:
    
    N = len(sys.argv)
    for i in range(1,N):
        value = None
        if sys.argv[i].startswith('--'):
            key = sys.argv[i][2:] #.replace('-','')
            SYS_ARGS[key] = 1			
            if i + 1 < N:
                value = sys.argv[i + 1] = sys.argv[i+1].strip()
            if key and value and not value.startswith('--'):
                SYS_ARGS[key] = value
                
        
        i += 2

if __name__ == '__main__' :
	#
	# Load information from the file ...
	if 'help' in SYS_ARGS :
		print (__doc__)
	else:
		try:
			_info = json.loads(open(SYS_ARGS['config']).read())
			if 'index' in SYS_ARGS :
				_index = int(SYS_ARGS['index'])
				_info = [_item for _item in _info if _info.index(_item) == _index]
				pass
			elif 'id' in SYS_ARGS :
				_info = [_item for _item in _info if 'id' in _item and _item['id'] == SYS_ARGS['id']]
			
			procs = 1 if 'procs' not in SYS_ARGS else int(SYS_ARGS['procs'])
			jobs = transport.factory.instance(provider='etl',info=_info,procs=procs)
			print ([len(jobs),' Jobs are running'])
			N = len(jobs)
			while jobs :
				x = len(jobs)
				jobs = [_job for _job in jobs if _job.is_alive()]
				if x != len(jobs) :
					print ([len(jobs),'... jobs still running'])
				time.sleep(1)
			print ([N,' Finished running'])
		except Exception as e:
			
			print (e)