
import com.atina.jde.session.JDESessionManager;
import com.jdedwards.system.connector.dynamic.ServerFailureException;
import oracle.e1.bssv.JP000010.CompanyManager;
import oracle.e1.bssv.JP000010.valueobject.CompanyKey;
import oracle.e1.bssv.JP000010.valueobject.GetCompany;
import oracle.e1.bssv.JP000010.valueobject.ShowCompany;
import oracle.e1.bssv.JPR01MO1.RI_AddressBookMediaObjectManager;
import oracle.e1.bssv.JPR01MO1.valueobject.ABGT_Publish;
import oracle.e1.bssv.JPR01MO1.valueobject.MOItem_Publish;
import oracle.e1.bssv.JPR01MO1.valueobject.RI_AddAddressBook;
import oracle.e1.bssv.JPR01MO1.valueobject.RI_ConfirmAddAddressBook;
import oracle.e1.bssv.util.J0100010.valueobject.Entity;
import oracle.e1.bssvfoundation.exception.BusinessServiceException;
import org.apache.commons.io.FileUtils;
import org.junit.platform.commons.logging.Logger;
import org.junit.platform.commons.logging.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import static org.junit.jupiter.api.Assertions.*;

class MainTest {

    private static final Logger logger = LoggerFactory.getLogger(MainTest.class);

    private static final String JDE_OUT_HANDLER = "JDEOutHandler";

    private String user;
    private String password;
    private String environment;
    private String role;

    private String jdeDefaultFolder;

    private int jdeSessionID;

    private JDESessionManager sessionManager;

    @org.junit.jupiter.api.BeforeEach
    void setUp() throws Exception {

        // -------------------------------------------------------------
        // Validate and load required environment variables
        // -------------------------------------------------------------

        logger.info(() -> "Validating required environment variables for JDE connection");

        String user = getRequiredEnv("JDE_TEST_USER");
        String password = getRequiredEnv("JDE_TEST_PASSWORD");
        String environment = getEnvOrDefault("JDE_TEST_ENVIRONMENT", "JDV920");
        String role = getEnvOrDefault("JDE_TEST_ROLE", "*ALL");

        sessionManager = new JDESessionManager(user, password, environment, role);
        jdeSessionID = sessionManager.login();

        logger.info(() -> "Obtained Session Id for JDE User: " + jdeSessionID);


    }

    @org.junit.jupiter.api.AfterEach
    void tearDown() {

        // ==============================================================
        // Log off from JDE session to clean up resources
        // ==============================================================

        logger.info(() -> "Logging off from JDE session and cleaning up resources");
        sessionManager.logoff();

    }

    @org.junit.jupiter.api.Test
    // @org.junit.jupiter.api.Disabled
    void testGetCompanyInfo() throws ServerFailureException, BusinessServiceException {


        // ============================================================================
        // Test JP000010 - GetCompany operation using CompanyManager with test data
        // ============================================================================

        CompanyManager companyManager = new CompanyManager();

        // Create and populate GetCompany value object for testing

        GetCompany getCompany = new GetCompany();

        // Set company name with a test value

        getCompany.setCompanyName("Prueba - Argentina - 28");

        // Set entity with a test value for address number

        Entity entity = new Entity();
        entity.setEntityId(28);
        getCompany.setAddressNumber(entity);

        // Set company key with a test value for company number

        CompanyKey companyKey = new CompanyKey();
        companyKey.setCompanyNumber("00028");

        getCompany.setCompanyKey(companyKey);

        ShowCompany result = companyManager.getCompany(getCompany);

        assertTrue(result.getShowCompanyResults().length == 1);
        assertTrue(result.getShowCompanyResults()[0].getCompanyKey().getCompanyNumber().equals("00028"));

    }

    @org.junit.jupiter.api.Test
    void testGetAB() throws ServerFailureException, BusinessServiceException, IOException {

        RI_AddressBookMediaObjectManager mgr = new RI_AddressBookMediaObjectManager();

        ABGT_Publish abgt = new ABGT_Publish();
        String moIn = "/tmp/MOInput/";
        String moOut = "/tmp/MOOutput/";

        RI_AddAddressBook addAB = new RI_AddAddressBook();
        addAB.setEntityName("Rocking8");  // Entity Name. Change for every add address book call.
        addAB.setEntityTypeCode("C");  // Entity Name. Change for every add address book call if required.
        addAB.setBusinessUnit("1"); // Business Unit. Change for every add address book call if required.


        MOItem_Publish moItemAdd = new MOItem_Publish();
        moItemAdd.setSzItemName("Readme.pdf");
        moItemAdd.setSzMoType("FILE");
        String filePath = moIn+"Readme.pdf";      //For FILE attachment type.
        File file = new File(filePath);
        FileInputStream fis = new FileInputStream(file);
        byte[] bytes = new byte[(int)file.length()];
        fis.read(bytes);
        moItemAdd.setSzData(bytes);

        MOItem_Publish moItemAdd1 = new MOItem_Publish();
        moItemAdd1.setSzMoType("TEXT");
        moItemAdd1.setSzData("This is a Text attachment for testing MTOM".getBytes());

        MOItem_Publish moItemAdd2 = new MOItem_Publish();
        moItemAdd2.setSzMoType("URL");
        moItemAdd2.setSzItemName("www.oracle.com");

        MOItem_Publish moItemAdd3 = new MOItem_Publish();
        moItemAdd3.setSzItemName("Green.gif");
        moItemAdd3.setSzMoType("FILE");
        String filePath3 = moIn+"Green.gif";      //For FILE attachment type.
        File file3 = new File(filePath3);
        FileInputStream fis3 = new FileInputStream(file3);
        byte[] bytes3 = new byte[(int)file3.length()];
        fis3.read(bytes3);
        moItemAdd3.setSzData(bytes3);

        MOItem_Publish[] moarray = new MOItem_Publish[4];
        moarray[0] = moItemAdd;
        moarray[1] = moItemAdd1;
        moarray[2] = moItemAdd2;
        moarray[3] = moItemAdd3;

        abgt.setMoItems(moarray);
        addAB.setMediaObject(abgt);

        RI_ConfirmAddAddressBook confirmAB = mgr.addAddressBookMO(addAB);
        Integer entityId = confirmAB.getEntityAddress().getEntity().getEntityId();
        System.out.println("Address Book Record created with Address book number  ::  "+entityId);

    }

    private String getRequiredEnv(String name) {
        String value = System.getenv(name);
        if (value == null || value.trim().isEmpty()) {
            fail("Missing required environment variable: " + name);
        }
        return value.trim();
    }

    private String getEnvOrDefault(String name, String defaultValue) {
        String value = System.getenv(name);
        return (value == null || value.trim().isEmpty()) ? defaultValue : value.trim();
    }

    private void assertNotBlank(String value, String name) {
        assertNotNull(value, name + " must not be null");
        assertFalse(value.trim().isEmpty(), name + " must not be blank");
    }

    public void setJDEDefaultFolderForMicroService(String environment) throws Exception {

        File tmpFolder = new File(FileUtils.getTempDirectory()
                .getAbsolutePath());

        jdeDefaultFolder = tmpFolder.getAbsolutePath().concat(File.separator)
                .concat("config").concat(File.separator)
                .concat(environment);

        System.setProperty("default_path", jdeDefaultFolder);


    }

}
