import logging

import pandas as pd

from .config import settings
from .db import get_DB_client
from .utils import elapsed_time
from .utils import print_table

logger = logging.getLogger(__name__)


class Query:
    def __init__(self):
        self.db = get_DB_client(settings.dbm)

    def run(self, sql, filename):
        logger.info(f"Reading SQL file in {sql}")
        with open(sql, "r") as f:
            query = f.read()
        logger.info("Running query")
        with elapsed_time as et:
            task = et.add_task("Running your query, elapsed time:")
            result = self.db.fetch_all(query)
            et.stop_task(task)
        logger.info("Finished running query")
        df = pd.DataFrame(result)
        print_table(df.head(50), "Your query first 50 results")
        logger.info(f"Saving result to {filename}")
        df.to_csv(filename, index=False, header=False)
