import os.path

import pandas

from tqsdk.tafunc import time_to_datetime

import warnings
warnings.filterwarnings('ignore')


class TQZOnePieceData:

    @classmethod
    def get_single_trade_day_df(cls, day_path: str, night_path: str):
        night_content = pandas.read_csv(night_path)
        day_content = pandas.read_csv(day_path)

        content = pandas.concat([night_content, day_content], axis=0)
        content['datetime'] = content['Timestamp_in'].apply(time_to_datetime)

        content.reset_index(inplace=True)
        del content['index']

        return content

    @classmethod
    def dump_format_data(cls):
        date_str_list = ['20230417', '20230418', '20230419', '20230420', '20230421',
                         '20230424', '20230425', '20230426', '20230427', '20230428']

        for date_str in date_str_list:
            target_fold = f'D:/ctp_data/level2_data/{date_str}'
            if os.path.exists(target_fold) is False:
                os.mkdir(target_fold)

            day_path = f'D:\ctp_data\CTP_{date_str}.csv'
            night_path = f'D:\ctp_data\CTP_{date_str}_night.csv'

            single_day_df = cls.get_single_trade_day_df(day_path=day_path, night_path=night_path)

            instruments = list(set(single_day_df['InstrumentID']))
            for instrument in instruments:
                single_instrument_df = single_day_df[single_day_df['InstrumentID'] == instrument]
                single_instrument_df.reset_index(inplace=True)
                del single_instrument_df['index']

                # print("instrument: " + str(instrument))
                # print("single_instrument_df: " + str(single_instrument_df))
                single_instrument_df.to_csv(f'{target_fold}/{instrument}', index=False)


if __name__ == '__main__':
    TQZOnePieceData.dump_format_data()