import tempfile
from datetime import datetime

import load.projects.cloud.loadtesting.server.admin.proto.db_pb2 as db_pb2
import load.projects.cloud.loadtesting.server.admin.proto.db_pb2_grpc as db_pb2_grpc

from load.projects.cloud.loadtesting.db import DB
from load.projects.cloud.loadtesting.server.admin.implementations.dump_schema import dump_schema


class DBServicer(db_pb2_grpc.DBServicer):
    def DumpPgSchema(self, request, context):
        """
        grpcurl -plaintext localhost:50055 DB/DumpPgSchema
        """
        with DB() as db:
            date_stamp = datetime.utcnow().date().isoformat().replace('-', '_')
            file_path = tempfile.mktemp(prefix=f'pg_schema_{date_stamp}_', suffix='.sql')
            dump_schema(db._session.bind, file_path)
        return db_pb2.DumpSchemaResponse(
            file_path=file_path,
        )
