// material-ui
import {
    Grid,
    Typography,
    Stack
} from '@mui/material';
import MainCard from "components/MainCard";
import {GEN_GFMIS_XML} from "utils/ApiPathConst";
import * as React from "react";
import * as HttpUtils from "utils/HttpUtils";
import * as DateUtils from "utils/DateUtils";

import Loadable from 'components/Loadable';
const LoadingComponent = Loadable(React.lazy(() => import('pages/extra-pages/LoadingComponent')));
const SearchForm = Loadable(React.lazy(() => import('./SearchForm')));
const EventTable = Loadable(React.lazy(() => import('./DataGrid')));
import titleBackgroundImg from 'assets/images/dashboard/gazette-bar.png'

const BackgroundHead = {
    backgroundImage: `url(${titleBackgroundImg})`,
    width: '100%',
    height: '100%',
    backgroundSize:'contain',
    backgroundRepeat: 'no-repeat',
    backgroundColor: '#0C489E',
    backgroundPosition: 'right'
}

// ==============================|| DASHBOARD - DEFAULT ||============================== //

const Index = () => {

    const [searchCriteria, setSearchCriteria] = React.useState({
        dateFrom: DateUtils.dateValue(new Date()),
        // dateFrom: DateUtils.dateValue(new Date().setDate(new Date().getDate()-14)),
    });
    const [onReady, setOnReady] = React.useState(false);

    React.useEffect(() => {
        setOnReady(true);
    }, [searchCriteria]);


    function downloadXML(input) {
        // console.log(input)
        HttpUtils.get({
            url: GEN_GFMIS_XML + "/today",
            params:{
                // dateTo: input.dateTo,
                dateFrom: input.dateFrom,
            },
            onSuccess: (responseData) => {
                console.log(responseData)
                const parser = new DOMParser();
                const xmlDoc = parser.parseFromString(responseData, 'application/xml');
                // Get the DCBHeader element
                const dcbHeader = xmlDoc.querySelector("DCBHeader");
                
                // Get the Receipt and Allocation elements
                const receiptElement = dcbHeader.querySelector("Receipt");
                const allocationElement = dcbHeader.querySelector("Allocation");
                const paymentMethodElements = Array.from(dcbHeader.querySelectorAll("PaymentMethod"));

                // Remove existing elements from DCBHeader
                dcbHeader.innerHTML = "";
                
                dcbHeader.appendChild(receiptElement);
                dcbHeader.appendChild(allocationElement);
                
                if (paymentMethodElements) {
                    paymentMethodElements.forEach((paymentMethodElement) => {
                    dcbHeader.appendChild(paymentMethodElement);
                });
                }
              
                const updatedXmlString = new XMLSerializer().serializeToString(xmlDoc);
                const filename = xmlDoc.querySelector('FileHeader').getAttribute('H_Filename');
                console.log(updatedXmlString)
                const blob = new Blob([updatedXmlString], { type: 'application/xml' });
                // Create a download link
                const link = document.createElement('a');
                link.href = URL.createObjectURL(blob);
                link.download = filename+'.xml';
        
                // Append the link to the document body
                document.body.appendChild(link);
        
                // Programmatically click the link to trigger the download
                link.click();
        
                // Clean up the link
                document.body.removeChild(link);
            }
          });
        // open(UrlUtils.GEN_GFMIS_XML + "/today?online=true") 
      }


    function applySearch(input) {
        setSearchCriteria(input);
    }

    function generateXML(input) {
        downloadXML(input);
    }

    return (
        !onReady ?
            <LoadingComponent/>
            :
            <Grid container sx={{minHeight: '87vh', backgroundColor: 'backgroundColor.default'}} direction="column">
                <Grid item xs={12}>
                    <div style={BackgroundHead}>
                        <Stack direction="row" height='70px' justifyContent="flex-start" alignItems="center">
                            <Typography ml={15} color='#FFF' variant="h4" sx={{ "textShadow": "0px 0px 25px #0C489E" }}>
                            GFMIS Generate XML
                            </Typography>
                        </Stack>
                    </div>
                </Grid>
                {/*row 1*/}
                <Grid item xs={12} md={12} lg={12} sx={{mb:-1}}>
                    <SearchForm 
                    applySearch={applySearch}
                    generateXML={generateXML}
                    searchCriteria={searchCriteria}
                    />
                </Grid>
                {/*row 2*/}
                <Grid item xs={12} md={12} lg={12}>
                    <MainCard elevation={0}
                            border={false}
                            content={false}
                            sx={{width: "-webkit-fill-available"}}
                    >
                        <EventTable
                            searchCriteria={searchCriteria}
                        />
                    </MainCard>
                </Grid>
            </Grid>
    );
};

export default Index;
