def get(self, project_db):
        SetupProjectDatabase.init(project_db)
        create_constit_ini_tables()

        if Constituents_cs.select().count() > 0:
            m = Constituents_cs.get()
            return {
                'using':
                True,
                'pests':
                [] if m.pest_coms is None else sorted(m.pest_coms.split(',')),
                'paths':
                [] if m.path_coms is None else sorted(m.path_coms.split(',')),
                'hmets':
                [] if m.hmet_coms is None else sorted(m.hmet_coms.split(',')),
                'salts':
                [] if m.salt_coms is None else sorted(m.salt_coms.split(','))
            }

        return {
            'using': False,
            'pests': [],
            'paths': [],
            'hmets': [],
            'salts': []
        }
def get_constituents_ini(project_db, ini_table, db_table, col_name):
    SetupProjectDatabase.init(project_db)
    items = [
        model_to_dict(v, backrefs=True, max_depth=1)
        for v in ini_table.select()
    ]
    constituents = []
    if Constituents_cs.select().count() > 0:
        c = model_to_dict(Constituents_cs.get())[col_name]
        names = [] if c is None else sorted(c.split(','))
        constituents = [{
            'id': v.id,
            'name': v.name
        } for v in db_table.select().where(db_table.name.in_(names))]

    return {'items': items, 'constituents': constituents}
    def write(self):
        table = db.Path_water_ini.select().order_by(db.Path_water_ini.id)
        items = db.Path_water_ini_item.select().order_by(
            db.Path_water_ini_item.name)
        query = prefetch(table, items)

        if table.count() > 0 and Constituents_cs.select().count() > 0:
            constits_row = Constituents_cs.select().first()
            constits = [] if constits_row.path_coms is None else sorted(
                constits_row.path_coms.split(','))
            if len(constits) > 0:
                with open(self.file_name, 'w') as file:
                    file.write(self.get_meta_line())

                    file.write(
                        utils.string_pad("name",
                                         direction="left",
                                         default_pad=25))
                    for c in constits:
                        file.write(utils.num_pad(c))
                    file.write("\n")

                    for row in query:
                        file.write(
                            utils.string_pad(row.name,
                                             direction="left",
                                             default_pad=25))
                        file.write("\n")

                        water_line = "  " + utils.string_pad(
                            "water", direction="left", default_pad=23)
                        benthic_line = "  " + utils.string_pad(
                            "benthic", direction="left", default_pad=23)
                        for item in row.path_waters:
                            water_line += utils.num_pad(item.water, decimals=3)
                            benthic_line += utils.num_pad(item.benthic,
                                                          decimals=3)

                        file.write(water_line)
                        file.write("\n")
                        file.write(benthic_line)
                        file.write("\n")
    def write(self):
        table = db.Pest_hru_ini.select().order_by(db.Pest_hru_ini.id)
        items = db.Pest_hru_ini_item.select().order_by(
            db.Pest_hru_ini_item.name)
        query = prefetch(table, items)

        if table.count() > 0 and Constituents_cs.select().count() > 0:
            constits_row = Constituents_cs.select().first()
            constits = [] if constits_row.pest_coms is None else sorted(
                constits_row.pest_coms.split(','))
            if len(constits) > 0:
                with open(self.file_name, 'w') as file:
                    file.write(self.get_meta_line())

                    file.write(
                        utils.string_pad("name",
                                         direction="left",
                                         default_pad=25))
                    for c in constits:
                        file.write(utils.num_pad(c))
                    file.write("\n")

                    for row in query:
                        file.write(
                            utils.string_pad(row.name,
                                             direction="left",
                                             default_pad=25))
                        file.write("\n")

                        soil_line = "  " + utils.string_pad(
                            "soil", direction="left", default_pad=23)
                        plant_line = "  " + utils.string_pad(
                            "plant", direction="left", default_pad=23)
                        for item in row.pest_hrus:
                            soil_line += utils.num_pad(item.soil, decimals=3)
                            plant_line += utils.num_pad(item.plant, decimals=3)

                        file.write(soil_line)
                        file.write("\n")
                        file.write(plant_line)
                        file.write("\n")
    def delete(self, project_db):
        SetupProjectDatabase.init(project_db)
        if Constituents_cs.select().count() > 0:
            project_base.db.execute_sql("PRAGMA foreign_keys = ON")
            Pest_hru_ini.delete().execute()
            Pest_water_ini.delete().execute()
            Path_hru_ini.delete().execute()
            Path_water_ini.delete().execute()
            Hmet_hru_ini.delete().execute()
            Hmet_water_ini.delete().execute()
            Salt_hru_ini.delete().execute()
            Salt_water_ini.delete().execute()
            return self.base_delete(project_db, 1, Constituents_cs,
                                    'Constituents')

        return 204
    def put(self, project_db):
        try:
            SetupProjectDatabase.init(project_db)
            parser = reqparse.RequestParser()
            parser.add_argument('pests', type=list, location='json')
            parser.add_argument('paths', type=list, location='json')
            parser.add_argument('hmets', type=list, location='json')
            parser.add_argument('salts', type=list, location='json')
            args = parser.parse_args(strict=False)

            pest_coms = None if args['pests'] is None or len(
                args['pests']) < 1 else ','.join(args['pests'])
            path_coms = None if args['paths'] is None or len(
                args['paths']) < 1 else ','.join(args['paths'])
            hmet_coms = None if args['hmets'] is None or len(
                args['hmets']) < 1 else ','.join(args['hmets'])
            salt_coms = None if args['salts'] is None or len(
                args['salts']) < 1 else ','.join(args['salts'])

            pest_ids = Pesticide_pst.select().where(
                Pesticide_pst.name.in_(args['pests']))
            Pest_hru_ini_item.delete().where(
                Pest_hru_ini_item.name.not_in(pest_ids)).execute()
            Pest_water_ini_item.delete().where(
                Pest_water_ini_item.name.not_in(pest_ids)).execute()

            path_ids = Pathogens_pth.select().where(
                Pathogens_pth.name.in_(args['paths']))
            Path_hru_ini_item.delete().where(
                Path_hru_ini_item.name.not_in(path_ids)).execute()
            Path_water_ini_item.delete().where(
                Path_water_ini_item.name.not_in(path_ids)).execute()
            """hmet_ids = Metals_mtl.select().where(Metals_mtl.name.in_(args['hmets']))
			Hmet_hru_ini_item.delete().where(Hmet_hru_ini_item.name.not_in(hmet_ids)).execute()
			Hmet_water_ini_item.delete().where(Hmet_water_ini_item.name.not_in(hmet_ids)).execute()

			salt_ids = Salts_slt.select().where(Salts_slt.name.in_(args['salts']))
			Salt_hru_ini_item.delete().where(Salt_hru_ini_item.name.not_in(path_ids)).execute()
			Salt_water_ini_item.delete().where(Salt_water_ini_item.name.not_in(path_ids)).execute()"""

            if Constituents_cs.select().count() > 0:
                q = Constituents_cs.update(pest_coms=pest_coms,
                                           path_coms=path_coms,
                                           hmet_coms=hmet_coms,
                                           salt_coms=salt_coms)
                result = q.execute()
            else:
                v = Constituents_cs.create(id=1,
                                           name='Constituents',
                                           pest_coms=pest_coms,
                                           path_coms=path_coms,
                                           hmet_coms=hmet_coms,
                                           salt_coms=salt_coms)
                result = 1 if v is not None else 0

            if result > 0:
                return 200

            abort(400,
                  message='Unable to update save changes to constituents.')
        except Exception as ex:
            abort(400, message="Unexpected error {ex}".format(ex=ex))