import { ObjectId } from "mongoose";
import { CallbackStrategyWithIdQuery, ResponseBase } from "../../../core/controllers/http_controller";
import { ExecProcessUseCase, IsHaveActiveProcessUseCase } from "../../../core/usecases/exec_process_usecase";
import { ReadByIdDataBaseModelUseCase } from "../../../core/usecases/read_by_id_database_model_usecase";
import { MongoIdValidation } from "../../../core/validations/mongo_id_validation";
import { ProcessWatcherAndDatabaseUpdateService } from "../../datasets/domain/create_dataset_scenario";
import { CalculationInstanceDBModel, ICalculationInstance } from "../models/calculations_instance_database_model";
import { Result } from "../../../core/helpers/result";
import { CreateFileUseCase } from "../../../core/usecases/create_file_usecase";

export class ExecCalculationInstanceProcessScenario extends CallbackStrategyWithIdQuery {
  idValidationExpression = new MongoIdValidation();
  call = async (id: string): ResponseBase =>
    (await new ReadByIdDataBaseModelUseCase<ICalculationInstance>(CalculationInstanceDBModel).call(id)).map(
      async (model) => {
        const fileOutPath = model.instancePath.pathNormalize() + "/form.json";
        return (await new IsHaveActiveProcessUseCase().call()).map(async () => {
          const execCommand = `${model.script
            } --path ${model.instancePath.pathNormalize()} --form ${fileOutPath}`.replace("\n", "");
      
          await new CreateFileUseCase().call(fileOutPath, Buffer.from(JSON.stringify(model.formBuilder)));
          await CalculationInstanceDBModel.findById(id).updateOne({
            processStatus: "RUN",
            lastProcessExecCommand: execCommand,
          });
          new ExecProcessUseCase().call(
            // @ts-expect-error
            `${model.project.rootDir}/`,
            execCommand,
            id,
            new ProcessWatcherAndDatabaseUpdateService(id as unknown as ObjectId, CalculationInstanceDBModel)
          );
          return Result.ok("OK");
        });
      }
    );
}
