import plac
import pyodbc


@plac.pos('query', 'SQL Query', type=str)
@plac.pos('mode', '', choices=['in', 'out', 'queryout'])
@plac.pos('csv_file', '', type=str)
@plac.opt('Server', 'Hostname or DSN', type=str)
@plac.opt('database', '', type=str)
@plac.opt('user', '', type=str)
@plac.opt('Password', '', type=str)
@plac.flg('charset', '')
@plac.opt('Codepage', '', type=str)
@plac.opt('errorlog', '', type=str)
def run(query, mode, csv_file, Server='localhost\\GLOBALCUBE', database='master', user='sa', Password='Mffu3011#', charset=False, Codepage='cp65001', errorlog='error.log'):
    dsn = f"dsn={Server};uid={user};pwd={Password}"
    if mode == 'queryout':
        queryout(dsn, query, csv_file, Codepage, errorlog)
        return
    print('This is madness')


def queryout(dsn, query, csv_file, codepage, errorlog):
    try:
        conn = pyodbc.connect(dsn)
        cursor = conn.cursor()
        cursor.execute(query)
        with open(csv_file, 'w', encoding=codepage, newline='\r\n') as fwh:
            while row := cursor.fetchone():
                fwh.write('\t'.join(map(str, row)))
    except pyodbc.InterfaceError as e:
        print(e.args[1])


if __name__ == '__main__':
    plac.call(run)