from model_data_api.model.base_model import BaseManager
from model_data_api.model.tab_model import TabDataSet
import datetime

class DataSetManager(BaseManager):
    def find_all(self):
        return self.get_json(self.session.query(TabDataSet).all())

    def find_single(self, id):
        return self.get_json(self.session.query(TabDataSet).filter_by(model_id = int(id)))

    def find_condition(self, **kwargs):
        return self.session.query(TabDataSet).filter(**kwargs)

    def create_obj(self,basic_data,raw_data):#,model_id,feature_name,set_name,set_data,set_number):
        # p = []
        # for data in raw_data:
        #     p.append(TabDataSet(model_name = basic_data['model_name'],
        #                         user_count = int(basic_data['count']),
        #                       feature_name=data['feature_name']
        #                       ))
        #
        # self.session.add_all(p)
        # self.session.commit()
        create = []
        updata = []
        for data in raw_data:

            query = self.session.query(TabDataSet).filter_by(model_name = basic_data['model_name'],feature_name = data['feature_name']).first()
            if not query:
                create.append(TabDataSet(model_name = basic_data['model_name'],
                                        user_count = int(basic_data['count']),
                                      feature_name=data['feature_name']
                                      ))
            else:
                self.session.query(TabDataSet).filter_by(model_name = basic_data['model_name'],feature_name = data['feature_name']).update({'user_count':int(basic_data['count']),'update_at':datetime.datetime.now()})
                # updata.append(TabDataSet(model_name = basic_data['model_name'],
                #                          user_count = int(basic_data['count']),
                #                          feature_name=data['feature_name'],
                #                          update_at = datetime.datetime.now()
                #                          ).check_existing())
        if create:
            self.session.add_all(create)
        # if updata:
        #     self.session.updata(updata)
        self.session.commit()



