import os
import pandas

def panda_to_csv(df, outdir, outfile, overwrite=True):
    dtype_arctypes = {'float64': 'DOUBLE', 'float32': 'FLOAT', 'int8': 'SHORT', 'int16': 'SHORT', 'int32': 'LONG',
                      'int64': 'DOUBLE', 'bool': 'TEXT Width 5', 'category': 'TEXT Width 255', 'object': 'TEXT Width '}
    #Create new directory to contain the main csv file and schema.ini file
    if not os.path.exists(outdir):
        os.mkdir(outdir)
    #Write out csv
    df.to_csv(os.path.join(outdir,outfile), index=False)
    #Write schema.ini file
    if os.path.exists(os.path.join(outdir, 'schema.ini')) and overwrite==False:
        print('schema.ini already exists in the output directory')
    else:
        schema_txt = '[{0}]\nFormat=CSVDelimited\nColNameHeader=True'.format(outfile)
        for i in range(0,df.shape[1]):
            schema_txt += '\nCol{0}={1} '.format(i+1, df.columns[i])
            if str(df.dtypes[i]) in dtype_arctypes:
                schema_txt += dtype_arctypes[str(df.dtypes[i])]
                if str(df.dtypes[i]) == 'object':
                    colwidth = str(int(df.iloc[:, i].str.len().max())*2)
                    schema_txt += colwidth
            else:
                schema_txt += 'TEXT Width 255'
        with open(os.path.join(outdir, "schema.ini"), "w") as text_file:
            text_file.write(schema_txt)