{-# LANGUAGE
    QuasiQuotes
  , OverloadedStrings
  #-}

module Templates.MainScripts where

import Text.Julius
import Data.Aeson.Types (Value (String))
import qualified Data.Text      as T
import qualified Data.Text.Lazy as LT

mainScripts :: T.Text -> LT.Text
mainScripts glossary = renderJavascript $ mainScripts' undefined
  where
    mainScripts' = [julius|

$(document).ready( function() {
  $("hr").replaceWith("<div class='ui divider'></div>");
  $("h1:not(.header), h2:not(.header), h3:not(.header), h4:not(.header)").addClass("ui header");
  $("table").addClass("ui table striped celled orange");
  $("#docs-markdown img").addClass("ui image centered");
  $("#navBar-menu-button").click(function(e) {
    $("#sideBar").sidebar('toggle');
  });
  $(".ui.accordion").accordion();
});

function deleteDef(t) {
  $.ajax({
    method: "DELETE",
    url: #{String glossary} + "/" + t,
    success: function(data) {
      console.log("DELETE RESPONSE: " + data);
      $("#" + t).remove();
    }
  });
}


|]


loginButton  = String "<a onclick=\"$('#login').modal('show');\" href=\"#\" id=\"login-button\">Login</a>"
logoutButton = String "<a onclick=\"signOut();\" href=\"#\" id=\"logout-button\">Logout</a>"


googleSignIn :: T.Text -> T.Text -> LT.Text
googleSignIn verify logout = renderJavascript $ googleSignIn' undefined
  where
    googleSignIn' = [julius|

function onSignIn(googleUser) {
  // Useful data for your client-side scripts:
  var profile = googleUser.getBasicProfile();
  console.log("ID: " + profile.getId()); // Don't send this directly to your server!
  console.log("Name: " + profile.getName());
  console.log("Image URL: " + profile.getImageUrl());
  console.log("Email: " + profile.getEmail());

  // The ID token you need to pass to your backend:
  var id_token = googleUser.getAuthResponse().id_token;
  console.log("ID Token: " + id_token);


  $.ajax({
    url: #{String verify},
    data: {"id_token": id_token},
    success: function(data) {
      console.log("LOGIN RESPONSE: " + data);
      $('#login-button').replaceWith(#{logoutButton});
      $('#login').modal('hide');
    }
  });
}

function signOut() {
  var auth2 = gapi.auth2.getAuthInstance();
  auth2.signOut().then(function () {
    console.log('User signed out.');
  });

  $.ajax({
    url: #{String logout},
    success: function(data) {
      console.log("LOGOUT RESPONSE: " + data);
      $('#logout-button').replaceWith(#{loginButton});
    }
  })
}

|]
