@extends('layouts.app')
@section('title')
  <i class="fas fa-cog mr-1 mt-1"></i> App API Access
@endsection

@section('content')
<div class="container-fluid pt-3">
    <div class="card">
      <div class="card-body">
        <div class="row mt-3">
          <div class="col-md-4">
            <div class="card card-primary card-outline">
              <div class="card-header">
                <h3 class="card-title"><i class="fas fa-list mr-1"></i> Active API tokens</h3>
              </div>
              <div class="card-body">
                <div class="" id="app_tokens"></div>
              </div>
            </div>
          </div>

          <div class="col-md-4">
            <div class="card card-primary card-outline">
              <div class="card-header">
                <h3 class="card-title"><i class="fas fa-plus mr-1"></i>Add new access token</h3>
              </div>
              <div class="card-body">
                <div class="input-group mb-3">
                  <input class="form-control" id="token" type="text" name="token" placeholder="Access token" disabled>
                  <div class="input-group-append">
                    <button id="tokenGenerator" class="btn btn-secondary" type="button">Generate</button>
                    <button id="addToken" class="btn btn-success" type="button">Add</button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
</div>
<script type="text/javascript">
$( document ).ready(function() {
  $('#menu-app-api').addClass('active');

  $.ajaxSetup({
      headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      }
  });

  $.ajax({
   type: "GET",
   url: "/app-api/fetch-tokens",
   success: function(response)
   {
    if(response.value_text == "")
    {
      $(document).Toasts('create', {
        title: 'API Access tokens',
        class: 'bg-info',
        autohide: true,
        delay: 5000,
        body: 'No active tokens found.',
        });
    }
    else
    {
      var api_tokens = response.value_text.split(" ");
      for(var i = 0; i < api_tokens.length; i++)
      {
        appendToken(api_tokens[i]);
      }
    }
   }
   
  });
  $("#addToken").click(function()
  {
    var add_token = $("#token").val();
    if(add_token != "")
    {
      $.ajax(
      {
        type: "POST",
        url: "/app-api/add-token",
        data: {add_token: add_token},
        success: function(response)
        {
          if(response.status)
          {
            appendToken(add_token);  
            $(document).Toasts('create', {
              title: 'Token added',
              class: 'bg-success',
              autohide: true,
              delay: 5000,
              body: 'Token added successfully.',

            });
            $("#token").val("");
          }
        }
      });
    }
    else
    {
      $(document).Toasts('create', {
        title: 'Token generation required.',
        class: 'bg-warning',
        body: 'An authentication token cannot be an empty string.',
      });
    }
  });

  $(document).on("click", ".deleteToken", function()
  {
    var delete_token = $(this).data("token");
    $.ajax({
      type: "POST",
      url: "/app-api/remove-token",
      data: {remove_token: delete_token},
      success: function(response)
      {
        if(response.status)
        {
          $("#token_"+delete_token).remove();

          $(document).Toasts('create', {
            title: 'Token removed',
            class: 'bg-success',
            autohide: true,
            delay: 5000,
            body: 'Token removed successfully.',
          });
        }
      }
    });
  });
// set the length of the string
var stringLength = 32;

// list containing characters for the random string
var stringArray = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];

$("#tokenGenerator").click(function (){

    var rndString = "";

    // build a string with random characters
    for (var i = 1; i < stringLength; i++) { 
        var rndNum = Math.ceil(Math.random() * stringArray.length) - 1;
        rndString = rndString + stringArray[rndNum];
    };
    
    $("#token").val(rndString);

});

function appendToken(token)
{
  
  $("#app_tokens").append('<div class="input-group mb-3" id="token_'+token+'">\
        <input class="form-control" id="" type="text" placeholder="Access token" value="'+token+'" disabled>\
        <div class="input-group-append">\
            <button class="btn btn-warning deleteToken" type="button" data-token="'+token+'">Revoke</button>\
        </div>\
      </div>');
}

});
</script>
@endsection
 
