#include "DetectorConstruction.h"
#include "G4HumanPhantomMessenger.h"

#include "G4RunManager.hh"
#include "G4UIcmdWithAString.hh"
#include "G4UIcmdWithoutParameter.hh"
#include "G4UIdirectory.hh"
#include "globals.hh"

G4HumanPhantomMessenger::G4HumanPhantomMessenger(DetectorConstruction* myUsrPhtm)
    : myUserPhantom(myUsrPhtm), bps(false) {
    phantomDir = new G4UIdirectory("/phantom/");
    phantomDir->SetGuidance("Set Your Phantom.");

    bpDir = new G4UIdirectory("/bodypart/");
    bpDir->SetGuidance("Add Body Part to Phantom");

    modelCmd = new G4UIcmdWithAString("/phantom/setPhantomModel", this);
    modelCmd->SetGuidance("Set sex of Phantom: MIRD, MIRDHead.");
    modelCmd->SetParameterName("phantomModel", true);
    modelCmd->SetDefaultValue("MIRD");
    modelCmd->SetCandidates("MIRD MIRDHead");
    modelCmd->AvailableForStates(G4State_PreInit, G4State_Idle);

    sexCmd = new G4UIcmdWithAString("/phantom/setPhantomSex", this);
    sexCmd->SetGuidance("Set sex of Phantom: Male or Female.");
    sexCmd->SetParameterName("phantomSex", true);
    sexCmd->SetDefaultValue("Female");
    sexCmd->SetCandidates("Male Female");
    sexCmd->AvailableForStates(G4State_PreInit, G4State_Idle);

    bodypartCmd = new G4UIcmdWithAString("/bodypart/addBodyPart", this);
    bodypartCmd->SetGuidance("Add a Body Part to Phantom");
    bodypartCmd->SetParameterName("bpName", true);
    bodypartCmd->AvailableForStates(G4State_PreInit, G4State_Idle);

    endCmd = new G4UIcmdWithoutParameter("/phantom/buildNewPhantom", this);
    endCmd->SetGuidance("Build your Phantom.");
    endCmd->AvailableForStates(G4State_PreInit, G4State_Idle);
}

G4HumanPhantomMessenger::~G4HumanPhantomMessenger() {
    delete modelCmd;
    delete sexCmd;
    delete bodypartCmd;
    delete endCmd;
    delete phantomDir;
    delete bpDir;
}

void G4HumanPhantomMessenger::SetNewValue(G4UIcommand* command, G4String newValue) {
    if (command == modelCmd) {
        myUserPhantom->SetPhantomModel(newValue);
    }
    if (command == sexCmd) {
        myUserPhantom->SetPhantomSex(newValue);
    }
    if (command == bodypartCmd) {
        AddBodyPart(newValue);
    }
    if (command == endCmd) {
        G4cout << " ****************>>>> NEW PHANTOM CONSTRUCTION <<<<***************** " << G4endl;
    }
}

void G4HumanPhantomMessenger::AddBodyPart(G4String newBodyPartSensitivity) {
    char* str = new char[newBodyPartSensitivity.length() + 1];

    strcpy(str, newBodyPartSensitivity.c_str());

    std::string bpart = strtok(str, " ");

    std::string sensitivity = strtok(NULL, " ");

    if (sensitivity == "yes") {
        bps = true;
    } else {
        bps = false;
    }

    G4cout << " >>> Body Part = " << bpart << "\n"
           << " >>> Sensitivity = " << sensitivity << G4endl;

    myUserPhantom->SetBodyPartSensitivity(bpart, bps);
}
