<script>
    // import axios from 'axios';
    // import {onMount} from 'svelte';
    import TableDropdown from "components/Dropdowns/TableDropdown.svelte";

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


    export let filter_action;
    export let checked_vals;
    let footprint;
    let promise;
    let checkbox_vals = [];
    // let checked_vals = [];

    export const wgResponse = null;
    export let filter;

    // function getCookie(name) {
    //     let cookieValue = null;
    //     if (document.cookie && document.cookie !== '') {
    //         const cookies = document.cookie.split(';');
    //         for (let i = 0; i < cookies.length; i++) {
    //             const cookie = cookies[i].trim();
    //             // Does this cookie string begin with the name we want?
    //             if (cookie.substring(0, name.length + 1) === (name + '=')) {
    //                 cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
    //                 break;
    //             }
    //         }
    //     }
    //     return cookieValue;
    // }

    async function getwgResponse(o_filter) {
        let csrftoken = getCookie('csrftoken');
        let authToken = getCookie('Token');
        console.log(csrftoken);
        console.log(authToken);
        console.log("-<>-"+checked_vals);
            const wgResponse = await fetch(
                    '/api2/wgClients?filter='+o_filter, {
                        method: 'GET',
                        credentials: 'include',
                        mode: 'same-origin',
                        headers: {
                          'X-CSRFToken': csrftoken,
                          'Authorization': "Token "+authToken,
                          'Accept': 'application/json',
                          'Content-Type': 'application/json',

                            }
                        }
                );
            return await wgResponse.json();
        }

    let selectedID = new Set();

    const onCheckId = event => {
        filter_action = true;
        const row_id = event.target.value; 
        if (event.target.checked) {
            selectedID.add(row_id);
            checked_vals.push(row_id);
        } else {
            selectedID.delete(row_id);
            const index = checked_vals.indexOf(row_id);
            checked_vals.splice(index, 1);
        }

        selectedID = selectedID;
        console.log(checked_vals);
    };

    const onSelectAll = event => {
        filter_action = true;
        console.log("Select All...");
        console.log(checkbox_vals);

        if (event.target.checked) {
            selectedID = new Set(checkbox_vals);
        } else {
            selectedID.clear();
        } 
        selectedID = selectedID;
        checked_vals = checkbox_vals;
    };

    // let promise = getwgResponse();
    
    async function promise_handler(filter){

        checkbox_vals = []
        const wg_promise = getwgResponse(filter);
        const wg_resp = await wg_promise;

        console.log("[+] ID Arrays");
        console.log(wg_resp);


        let i = 0;

        // for (let i = 0; i < wg_resp.length; i++) {

        // for ( const x in wg_resp.json) {
        //         for ( const v in x ) {
        //                 console.log(v);
        //                 // console.log(v["id"]);
        //             }
        // }

        wg_resp.forEach(function (arrayItem) {
            var x = arrayItem.id;
                checkbox_vals.push(x);
            console.log(x);
        });

         console.log("IDs ->");
         console.log(checkbox_vals);

        return wg_resp

    }
    $: filter ?
        // promise = getwgResponse(filter) : promise = getwgResponse("");
        promise = promise_handler(filter) : promise = promise_handler("");

    export let color = "light";

</script>

{#await promise}

    <div
      class="rounded relative flex flex-col min-w-0 break-words w-full mb-6 shadow-lg rounded {color === 'light' ? 'bg-white' : 'bg-red-800 text-white'}"
    >
      <div class="rounded bg-white mb-0 px-6 py-6">
        <div class="text-center w-full">
          <div class="relative pt-1">
              <div class="flex mb-2 items-center justify-between">
                <div>
                  <span class="text-xs font-semibold inline-block py-1 px-2 uppercase rounded-full text-orange-600 bg-orange-200">
                    Task in progress
                  </span>
                </div>
                <div class="text-right">
                  <span class="text-xs font-semibold inline-block text-orange-600">
                    0%
                  </span>
                </div>
              </div>
              <div class="overflow-hidden h-2 mb-4 text-xs flex rounded bg-orange-200">
                 <div style="width:30%" class="shadow-none flex flex-col text-center whitespace-nowrap text-white justify-center bg-orange-500"></div>
              </div>
            </div>
        </div>
      </div>
    </div>

{:then wgProfileData}

<div
  class="relative flex flex-col min-w-0 break-words w-full mb-6 shadow-lg rounded {color === 'light' ? 'bg-white' : 'bg-red-800 text-white'}"
>
  <div class="rounded-t mb-0 px-4 py-3 border-0">
    <div class="flex flex-wrap items-center">
      <div class="relative w-full px-4 max-w-full flex-grow flex-1">
        <h3
          class="font-semibold text-lg {color === 'light' ? 'text-blueGray-700' : 'text-white'}"
        >
          User Profiles
        </h3>
      </div>
    </div>
  </div>
  <div class="block w-full overflow-x-auto">
    <!-- Projects table -->
    <table class="w-full striped hover">
      <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 {color === 'light' ? 'bg-blueGray-300 text-blueGray-500 border-blueGray-100' : 'bg-red-700 text-red-200 border-red-600'}"
          >
          <input id="select-all" checked={selectedID.size == wgProfileData.length} on:change={onSelectAll} type="checkbox" value="" class="w-4 h-4 text-teal-600 bg-gray-100 rounded border-gray-300 focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600">
              <label for="default-checkbox" class="ml-2 text-sm font-bold text-blueGray-500 dark:text-gray-300">#</label>
          </th>
          <th
            class="px-6 align-middle border border-solid py-3 text-sm uppercase border-l-0 border-r-0 whitespace-nowrap font-semibold text-left {color === 'light' ? 'bg-blueGray-50 text-blueGray-500 border-blueGray-100' : 'bg-red-700 text-red-200 border-red-600'}"
          >
            Name
          </th>
          <th
            class="px-6 align-middle border border-solid py-3 text-sm uppercase border-l-0 border-r-0 whitespace-nowrap font-semibold text-left {color === 'light' ? 'bg-blueGray-50 text-blueGray-500 border-blueGray-100' : 'bg-red-700 text-red-200 border-red-600'}"
          >
            Mail
          </th>
          <th
            class="px-6 align-middle border border-solid py-3 text-sm uppercase border-l-0 border-r-0 whitespace-nowrap font-semibold text-left {color === 'light' ? 'bg-blueGray-50 text-blueGray-500 border-blueGray-100' : 'bg-red-700 text-red-200 border-red-600'}"
          >
            Assigned IP
          </th>
          <th
            class="px-6 align-middle border border-solid py-3 text-sm uppercase border-l-0 border-r-0 whitespace-nowrap font-semibold text-left {color === 'light' ? 'bg-blueGray-50 text-blueGray-500 border-blueGray-100' : 'bg-red-700 text-red-200 border-red-600'}"
          >
            Allowed IP
          </th>
          <th
            class="uppercase px-6 align-middle border border-solid py-3 text-sm uppercase border-l-0 border-r-0 whitespace-nowrap font-semibold text-left {color === 'light' ? 'bg-blueGray-50 text-blueGray-500 border-blueGray-100' : 'bg-red-700 text-red-200 border-red-600'}"
          >
            Status
          </th>
          <th
            class="px-6 align-middle border border-solid py-3 text-sm uppercase border-l-0 border-r-0 whitespace-nowrap font-semibold text-left {color === 'light' ? 'bg-blueGray-50 text-blueGray-500 border-blueGray-100' : 'bg-red-700 text-red-200 border-red-600'}"
            >
            Created Time
          </th>
          <th
            class="px-6 align-middle border border-solid py-3 text-sm uppercase border-l-0 border-r-0 whitespace-nowrap font-semibold text-left {color === 'light' ? 'bg-blueGray-50 text-blueGray-500 border-blueGray-100' : 'bg-red-700 text-red-200 border-red-600'}"
            >
            Action
          </th>
        </tr>
      </thead>
      <tbody>
        {#each wgProfileData as infRows}
            <tr class="{infRows.enabled != true ? 'bg-red-50 text-red-500 text-sm' : 'text-blueGray-500 bg-white text-sm'} ">
                
                <td
                  class="bg-blueGray-300 border-t-8 px-4 align-middle border-l-0 border-r-0 text-sm whitespace-nowrap p-4 rounded"
                >
                <input checked={selectedID.has(infRows.id)} id="{ infRows.id }" type="checkbox" value="{ infRows.id }" on:change={onCheckId} class="w-4 h-4 text-teal-600 bg-gray-100 rounded border-gray-300 focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600">
                    <label for="default-checkbox" class="ml-2 text-sm font-bold text-blueGray-500 dark:text-gray-300">{ infRows.data_id }</label>
                </td>

                <td
                  class="border-t-8 px-6 align-middle border-l-0 border-r-0 text-sm whitespace-nowrap p-4"
                >
                    { infRows.name }
                </td>
                <td
                  class="border-t-8 px-6 align-middle border-l-0 border-r-0 text-sm whitespace-nowrap p-4"
                >
                    { infRows.email }
                </td>

                <td
                  class="border-t-8 px-6 align-middle border-l-0 border-r-0 text-sm whitespace-nowrap p-4"
                >
                    { infRows.allocated_ips }
                </td>

                <td
                  class="border-t-8 px-6 align-middle border-l-0 border-r-0 text-sm whitespace-nowrap p-4"
                >
                    { infRows.allowed_ips }
                </td>

                <td
                  class="border-t-8 px-6 align-middle border-l-0 border-r-0 text-sm whitespace-nowrap p-4 font-bold"
                >
                    { infRows.enabled != true ? 'Disabled' : 'Enabled' }
                </td>

                <td
                  class="border-t-8 px-6 align-middle border-l-0 border-r-0 text-sm whitespace-nowrap p-4"
                >
                    { infRows.updated_at }
                </td>
                <td
                  class="border-t-8 px-6 align-middle border-l-0 border-r-0 text-sm whitespace-nowrap p-4 text-right"
                >
                <TableDropdown bind:filter={ filter } bind:wg_id={ infRows.id } bind:wg_user_state={ infRows.enabled } />
                </td>
            </tr>
        {/each}
      </tbody>
    </table>
  </div>
</div>

{:catch error}

    <div class="h-screen w-full">
        <div
          class="relative flex flex-col min-w-0 break-words w-full mb-6 shadow-lg rounded {color === 'light' ? 'bg-white' : 'bg-red-800 text-white'}"
        >
          <div class="rounded-t bg-red-200 mb-0 px-6 py-6">
            <div class="text-center flex justify-between">
              <h6 class="uppercase text-blueGray-500 text-xl font-bold">Error</h6>
            </div>
          </div>
          <div class="rounded-t mt-3 mb-3 px-4 py-3 border-0">
            <div class="flex flex-wrap items-center">
              <div class="relative w-full h-full px-4 max-w-full flex-grow flex-1">
                <p class="text-lg text-red-500"> {error.message} </p>
              </div>
            </div>
          </div>
        </div>
    </div>

{/await}
