from pot_libs.mysql_util.mysql_util import MysqlUtil


async def scope_by_sql(mid_sql, offset, limit):
    scope_event_type = ['over_gap_cur', 'over_gap_i', 'over_gap_pttl',
                        'over_gap_u', 'over_res_cur', 'over_rms_i',
                        'over_rms_pttl', 'over_rms_u', 'under_rms_u']
    sql = f"select * from point_1min_scope where {mid_sql} " \
          f"and fault_type in %s" \
          f"order by create_time desc limit {limit} offset {offset}"
    count_sql = f"select count(*) count from point_1min_scope where" \
                f" {mid_sql} and fault_type in %s"
    async with MysqlUtil() as conn:
        data = await conn.fetchall(sql, args=(scope_event_type,))
        count = await conn.fetch_value(count_sql, args=(scope_event_type,))
    return data, count


async def detail_data_by_es(pid, create_time):
    sql = f"select * from point_1min_scope where pid=%s and create_time=%s"
    async with MysqlUtil() as conn:
        data = await conn.fetchone(sql, args=(pid, create_time))
    return data


def get_source(hit):
    result = hit['_source']
    result['_id'] = hit['_id']
    return result


async def event_data_by_es(mtid, event_datetime, event_type):
    sql = f"select * from point_1min_event where mtid=%s and " \
          f"event_datetime=%s and event_type=%s"
    async with MysqlUtil() as conn:
        data = await conn.fetchone(sql,
                                   args=(mtid, event_datetime, event_type))
    return data
