<script>

    import PapaParse from 'papaparse';
    import { getCookie } from "components/Utils/CookieHandler.js";

    let onUpload;
    let dataToCSV = [];

    let prevDataToCSV;
    let allowedFiledExtensions = ['csv']; let maxFileSize = 3145728;
    let data = [];

    let placeholder = [
            "Name",
            "Email",
            "Code",
            "Organization"
        ];

    let headers = [
            "Name",
            "Email",
            "Code",
            "Organization"
        ];


    let newRow = [...placeholder];
    // bound to the uploaded file
    let uploader;

    async function postWGReg(data) {
        let csrftoken = getCookie('csrftoken');
        let authToken = getCookie('Token');
        console.log(csrftoken);
        console.log(authToken);
            const wgResponse = await fetch(
                    '/api2/wgBulkReg?', {
                        method: 'POST',
                        credentials: 'include',
                        mode: 'same-origin',
                        headers: {
                          'Authorization': "Token "+authToken,
                          'Accept': 'application/json',
                          'Content-Type': 'application/json',

                            },
                        body: JSON.stringify(data)
                    });
            return await wgResponse.json();
        }
    
    $: {
            // Monitor props
        if (dataToCSV !== prevDataToCSV && dataToCSV.length !== 0) {
            prevDataToCSV = dataToCSV;
            const csvData = PapaParse.unparse(dataToCSV); // Change this to parser of yours <papaparse or django backed parser>
            onUpload ? onUpload(csvData) : console.log("CSV Data: ", csvData);
        }
    }

    function submitRegistration(){
            console.log("I'm submitting registration data");
            console.log(data);
        }
    function clearData(){
            data = [];
        }

    function addRow(){
            console.log("Should add row here...");
            data = [...data, [...newRow]];
            newRow = placeholder;
            placeholder = ["", "", "", ""];
        }
    function checkData(){
            console.log(data);
        }

    function deleteRow(rowTarget) {
            data = data.filter(row  => row != rowTarget);
            console.log(data);
        }

    function uploadFile(event) {
        event.preventDefault();
        const file = uploader.files[0];

        console.log(file);

        const fileExtensionArray = file.type.split("/");
        const fileExtension = fileExtensionArray[fileExtensionArray.length-1];

        if (file.size > maxFileSize) {
            console.log("Your stupid file is too big");
            return;
        }

        if (fileExtension.includes('csv') && file.size < maxFileSize) {
            console.log("Will proceed with your file after the infrastructure ready...");
            const csvData = PapaParse.parse(
                file,
                {
                    complete: (results) => {
                        onUpload ? onUpload(results.data) : data = results.data;
                    }
                }
            );
        } else if (allowedFiledExtensions.includes(fileExtension)) {
            onUpload ? onUpload(file) : console.log("Broken file, plain content : ", file);
        } else {
            console.log("Wrong extension stupid ...");
        }
    }

</script>


<div
  class="relative flex flex-col min-w-0 break-words w-full mb-6 shadow-lg rounded-lg bg-blueGray-100 border-0"
>
  <div class="rounded bg-white mb-0 px-6 py-6">
    <div class="text-center flex justify-between">
      <h6 class="mt-3 text-blueGray-700 text-xl font-bold">Action</h6>
      <div class="">

        <label class="block mb-2 text-sm font-medium text-gray-900 dark:text-white" for="file_input">Upload file</label>
        <input class="block w-full text-sm text-teal-500 border border-teal-300 rounded-lg cursor-pointer bg-teal-50 dark:text-teal-400 focus:outline-none dark:bg-teal-700 dark:border-teal-600 dark:placeholder-teal-400" 
               aria-describedby="file_input_help" 
               bind:this={uploader}
               on:change={uploadFile}
               id="file_input" 
               type="file"
               />
        <p class="mt-1 text-sm text-gray-500 dark:text-gray-300" id="file_input_help">SVG, PNG, JPG or GIF (MAX. 800x400px).</p>

        <button
          class="mt-3 bg-teal-500 text-white active:bg-red-500 font-bold uppercase text-xs px-4 py-2 rounded shadow hover:shadow-md outline-none focus:outline-none mr-1 ease-linear transition-all duration-150"
          type="button"
        >
          Search
        </button>
        <button
          class="mt-3 bg-teal-500 text-white active:bg-red-500 font-bold uppercase text-xs px-4 py-2 rounded shadow hover:shadow-md outline-none focus:outline-none mr-1 ease-linear transition-all duration-150"
          type="button"
        >
          Filter
        </button>
        <button
          class="mt-3 bg-amber-500 text-white active:bg-red-500 font-bold uppercase text-xs px-4 py-2 rounded shadow hover:shadow-md outline-none focus:outline-none mr-1 ease-linear transition-all duration-150"
          type="button"
        >
          Apply to System
        </button>
        <button
          class="mt-3 bg-red-600 text-white active:bg-red-500 font-bold uppercase text-xs px-4 py-2 rounded shadow hover:shadow-md outline-none focus:outline-none mr-1 ease-linear transition-all duration-150"
          type="button"
        >
          Backup
        </button>
      </div>
    </div>
  </div>
</div>

<div
  class="relative flex flex-col min-w-0 break-words w-full mb-6 shadow-lg rounded-lg border-0 bg-blueGray-200"
>
  <div class="rounded mb-0 px-6 py-6">
    <table class="items-center w-full bg-transparent">
        <thead>
            <tr>
                <th
                    class="px-4 align-middle border border-solid py-3 text-sm uppercase border-l-0 border-r-0 whitespace-nowrap font-semibold text-left bg-blueGray-50 text-blueGray-500 border-blueGray-100"
                >
                    #
                </th>
                {#each headers as cell}
                <th
                    class="px-4 align-middle border border-solid py-3 text-sm uppercase border-l-0 border-r-0 whitespace-nowrap font-semibold text-left bg-blueGray-50 text-blueGray-500 border-blueGray-100"
                >
                    { cell }
                </th>
                {/each}
                <th
                    class="px-4 align-middle border border-solid py-3 text-sm uppercase border-l-0 border-r-0 whitespace-nowrap font-semibold text-left bg-blueGray-50 text-blueGray-500 border-blueGray-100"
                >
                    Action
                </th>
            </tr>
        </thead>
        <tbody>
      {#each data as row, i}
          {#if row.length = 4}
                <tr class="border-t-8 text-blueGray-500 bg-white text-sm">
                       <td 
                        class="border-blueGray-200 px-6 align-middle text-sm whitespace-nowrap p-2"
                        > 
                        {i + 1}
                       </td>
                    {#each row as cell}
                       <td 
                        class="px-4 align-middletext-sm whitespace-nowrap p-2 focus:outline-none focus:bg-teal-400 focus:text-white focus:text-base"
                        >
                            <input
                              type="text"
                              placeholder="Search here..."
                              class="border-0 placeholder-blueGray-300 text-blueGray-600 relative bg-white bg-white rounded text-sm shadow outline-none focus:outline-none focus:ring-2 focus:ring-teal-500 w-full pl-10"
                                bind:value={cell} 
                            />
                       </td>
                    {/each}
                    <td
                     class="px-6 align-middle text-sm whitespace-nowrap p-2"
                     >
                        <button
                          class="bg-red-500 text-white active:bg-red-500 font-bold uppercase text-xs px-2 py-1 rounded shadow hover:shadow-md outline-none focus:outline-none mr-1 ease-linear transition-all duration-150"
                          type="button"
                          on:click={ () => deleteRow(row) }
                        >
                            <i class="fas fa-times"></i>
                        </button>
                    </td>

                </tr>
          {/if}
      {/each}
            <tr class="text-blueGray-500 border-t-8 bg-white text-sm">
                <td 
                 class="border-blueGray-200  px-6 align-middle border-l-0 border-r-0 text-sm whitespace-nowrap p-2"
                 > 
                 #
                </td>
                {#each newRow as cell}
                <td
                    class="px-6 align-middletext-sm whitespace-nowrap p-2 focus:outline-none focus:bg-teal-400 focus:text-white focus:text-base"
                >
                            <input
                              type="text"
                              placeholder="Search here..."
                              class="border-0 placeholder-blueGray-300 text-blueGray-600 relative bg-white bg-white rounded text-sm shadow outline-none focus:outline-none focus:ring-2 focus:ring-teal-500 w-full pl-10"
                                bind:value={cell} 
                            />
                </td>
                {/each}
                <td
                 class=" px-6 align-middle border-l-0 border-r-0 text-sm whitespace-nowrap p-2"
                 >
                    <button
                      class="bg-teal-500 text-white active:bg-red-500 font-bold uppercase text-xs px-2 py-1 rounded shadow hover:shadow-md outline-none focus:outline-none mr-1 ease-linear transition-all duration-150"
                      type="button"
                      on:click={ addRow }
                    >
                        <i class="fas fa-plus"></i>
                    </button>
                </td>
            </tr>
        </tbody>
    </table>
  </div>

  <div class="bg-white mb-0 px-6 py-6">

    <button
      class="mt-3 bg-teal-500 text-white active:bg-red-500 font-bold uppercase text-xs px-4 py-2 rounded shadow hover:shadow-md outline-none focus:outline-none mr-1 ease-linear transition-all duration-150"
      type="button"
      on:click={ () => postWGReg(data)}
    >
     Submit Registration
    </button>

    <button
      class="mt-3 bg-amber-500 text-white active:bg-red-500 font-bold uppercase text-xs px-4 py-2 rounded shadow hover:shadow-md outline-none focus:outline-none mr-1 ease-linear transition-all duration-150"
      type="button"
      on:click={ () => checkData() }
    >
     Check Current Data
    </button>

    <button
      class="mt-3 bg-red-400 text-white active:bg-red-500 font-bold uppercase text-xs px-4 py-2 rounded shadow hover:shadow-md outline-none focus:outline-none mr-1 ease-linear transition-all duration-150"
      type="button"
      on:click={ () => clearData() }
    >
     Clear Data
    </button>

  </div>
</div>
