<!DOCTYPE html>
<html lang="en">
  <head>
 <!-- client link-->
  <script src="https://cdn.freshdev.io/assets/app-client@2.js"></script>
  <!--End client link-->
   <!-- crayons link-->
   <script
   type="module"
   src="https://cdn.jsdelivr.net/npm/@freshworks/crayons@v4/dist/crayons/crayons.esm.js"
 ></script>
 <script
   nomodule
   src="https://cdn.jsdelivr.net/npm/@freshworks/crayons@v4/dist/crayons/crayons.js"
 ></script>
   <!--End crayons link-->
    <!-- ALert links-->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
      integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tagsinput/0.8.0/bootstrap-tagsinput.css"
      integrity="sha512-xmGTNt20S0t62wHLmQec2DauG9T+owP9e6VU8GigI0anN7OXLip9i7IwEhelasml2osdxX71XcYm6BQunTQeQg=="
      crossorigin="anonymous" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tagsinput/0.8.0/bootstrap-tagsinput.min.js"
      integrity="sha512-9UR1ynHntZdqHnwXKTaOm1s6V9fExqejKvg5XMawEMToW4sSw+3jtLrYfZPijvnwnnE8Uol1O9BcAskoxgec+g=="
      crossorigin="anonymous"></script>
  
    <style>
      body{
        font-size: 10px;
      }
      .dropdown {
        width: 10%;
        color: black;
        border: 5;
      }
  
      #error_div {
        color: red;
      }
  
      .select2-container {
        width: 70%;
      }
  
      .select2-container--default {
        width: 80% !important;
      }
  
      .select2-locked {
        padding: 0px !important;
      }
  
      .app-config {
        margin: 10px 20px;
      }
  
      .required:after {
        content: " *";
        color: red;
      }
  
      .error {
        color: red;
      }
  
      /* model css */
      /* The Modal (background) */
      .modal {
        display: none;
        /* Hidden by default */
        position: fixed;
        /* Stay in place */
        z-index: 1;
        /* Sit on top */
        padding-top: 30px;
        /* Location of the box */
        left: 0;
        top: 0;
        width: 100%;
        /* Full width */
        height: 100%;
        /* Full height */
        overflow: auto;
        /* Enable scroll if needed */
        background-color: rgb(0, 0, 0);
        /* Fallback color */
        background-color: rgba(0, 0, 0, 0.4);
        /* Black w/ opacity */
      }
  
      /* Modal Content */
      .modal-content {
        background-color: #fefefe;
        margin: auto;
        padding: 20px;
        border: 1px solid #888;
        width: 50%;
      }
  
      /* The Close Button */
      .editclose {
        color: #aaaaaa;
        float: right;
        font-size: 28px;
        font-weight: bold;
      }
  
      .editclose:hover,
      .editclose:focus {
        color: #000;
        text-decoration: none;
        cursor: pointer;
      }
  
      .createclose {
        color: #aaaaaa;
        float: right;
        font-size: 28px;
        font-weight: bold;
      }
  
      .createclose:hover,
      .createclose:focus {
        color: #000;
        text-decoration: none;
        cursor: pointer;
      }
  
      .table-action-icon {
        padding-right: 5px;
      }
  
      .table-header-but {
        padding: 5px;
      }
  
      .row-div {
        /* margin-right: 20px; */
        display: inline-block;
        max-width: 20%;
        margin-right: 10px;
      }
  
      .table-bottom {
        width: 100%;
        text-align: center;
      }
  
  
  
      .panel {
        background-color: #f0f1f5;
        padding: 35px 25px;
      }
  
      .panel-box {
        background-color: #e9ebf0;
        /* margin-bottom: 10px; */
        padding: 10px 15px;
        border: 1px lightgrey solid;
      }
  
      .i-mt-12 {
        margin-top: 12px;
      }
  
      .i-pt-12 {
        padding-top: 12px;
      }
  
      .app-img {
        width: 60px;
        padding-right: 15px;
      }
  
      .disp-flex {
        display: inline-flex;
      }
  
      .web-store {
        padding: 5px;
      }
  
      .role-padd {
        margin-left: 12px;
        margin-right: 12px;
        margin-top: 12px;
      }
  
      #pop-error {
        display: none;
      }
  
      #load-spinn-mod {
        display: none;
      }
  
      .alert-primary1 {
        display: none;
      }
  
      .alert-danger1 {
        display: none;
      }
  
      /* styles for headings */
      .app-title {
        font-size: 20px;
        margin-bottom: 10px;
      }
  
      .app-title,
      .nav-button,
      .section-title {
        text-transform: uppercase;
      }
  
      .app-title,
      .section-title {
        font-weight: 400;
        letter-spacing: 2px;
      }
  
      .card-body {
        /* align-content: center; */
        background-color: #F0F0F0;
      }
  
  
      body {
        font-family: Arial, Helvetica, sans-serif;
      }
  
      /* The Modal (background) */
      .modal {
        display: none;
        /* Hidden by default */
        position: fixed;
        /* Stay in place */
        z-index: 1;
        /* Sit on top */
        padding-top: 30px;
        /* Location of the box */
        left: 0;
        top: 0;
        width: 100%;
        /* Full width */
        height: 100%;
        /* Full height */
        overflow: auto;
        /* Enable scroll if needed */
        background-color: rgb(0, 0, 0);
        /* Fallback color */
        background-color: rgba(0, 0, 0, 0.4);
        /* Black w/ opacity */
      }
  
      /* Modal Content */
      .modal-content {
        background-color: #fefefe;
        margin: auto;
        padding: 20px;
        border: 1px solid #888;
        width: 80%;
      }
  
      /* The Close Button */
      .close {
        color: #aaaaaa;
        float: right;
        font-size: 28px;
        font-weight: bold;
      }
  
      .close:hover,
      .close:focus {
        color: #000;
        text-decoration: none;
        cursor: pointer;
      }
  
      /* styles for cards */
  
      /* Float four columns side by side */
      .clmn {
  
        width: 70%;
        padding: 30px;
      }
  
      /* Remove extra left and right margins, due to padding */
      .rw {
        margin: 0 -5px;
      }
  
      /* Clear floats after the columns */
      .rw:after {
        content: "";
        display: table;
        clear: both;
      }
  
      .btn.placeholderButton {
        width: 185px;
      }
  
  
      /* Style the counter cards */
      .cards {
        box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
        padding: 16px;
        text-align: center;
        background-color: #f1f1f1;
      }
  
      /* cemter card */
  
      .configuration {
        padding: 25px;
      }
  
      .fade-in-below {
        animation: fadeInBelow .3s ease-in-out;
        margin-left: 50px;
        margin-right: 50px;
      }
  
      .mar-bot {
        margin-bottom: 30px;
      }
  
      .card,
      .centered-card,
      .error-box,
      .form-input {
        background-color: #fff;
      }
  
      .card,
      .centered-card {
        padding: 25px;
        box-shadow: 0 10px 20px rgb(0 0 0 / 10%), 0 20px 40px rgb(0 0 0 / 5%);
        border-radius: 8px;
      }
  
      .section-title {
        font-size: 18px;
        margin-bottom: 15px;
        margin-top: 0;
      }
  
      .app-title,
      .nav-button,
      .section-title {
        text-transform: uppercase;
      }
  
      .app-title,
      .section-title {
        font-weight: 400;
        letter-spacing: 2px;
      }
  
      .section-title>span {
        vertical-align: middle;
      }
  
      .ember-basic-dropdown {
        position: relative;
      }
  
      .ember-basic-dropdown,
      .ember-basic-dropdown-content,
      .ember-basic-dropdown-content *,
      .ember-power-select-dropdown *,
      .es-control,
      .es-options {
        box-sizing: border-box;
      }
  
      .ember-power-select-multiple-trigger {
        padding: 2px 24px 2px 8px;
      }
  
      .ember-power-select-trigger {
        background: #fff;
        /* border: none; */
        border: 1px solid #cfd7df;
        border-radius: 4px;
        font-size: 14px;
        font-weight: 400;
        /* padding: 1px 24px 1px 12px; */
        overflow-y: hidden;
        min-height: 34px;
      }
  
  
      /* styles for headings */
      .app-title {
        font-size: 24px;
        margin-bottom: 20px;
      }
  
      .bootstrap-tagsinput {
        width: 600px;
      }
     .bootstrap-tagsinput .tag {
        background: #b0c4de;
        padding: 2.5px;
        font-size: 12px;
        font-weight: 500;
      }
      /* #mandatoryTime{ */
      .required:after {
        /* content: "*"; */
        position: relative;
        display: inline-block;
        inset-block-start: 2px;
        font-size: 14px;
        color: rgb(215, 45, 48);
        padding-inline-start: 2px;
        font-weight: 700;
      }
    </style>
<script type= "text/javascript">
 
var headers = {"Authorization": "Basic <%= encode(iparam.api_key) %>",'Content-Type': 'application/json'};

var options = { headers: headers };
var fd_domain, fd_api_key,config,msg;
var  client;
var group_list = [];var agent_list = [];var agent_list_ = [];
//getConfig method
function getConfigs(configs) {
	console.log("Get configs.....",configs);
    let fd_api_key = document.getElementById('fd-api-key');
    let fd_domain = document.getElementById('fd-domain');
		let fd_fields = document.getElementById("fd_fields");
    if(configs.api_key) fd_api_key.value = configs.api_key;
    if(configs.domain) fd_domain.value = configs.domain;
    if (configs.toemail) {$('#add-tag').tagsinput('add', configs.toemail)};
    if(configs.fd_fields) fd_fields.value = configs.fd_fields;
    config=configs;


}

//validate()
function validate(){        
  let isValid = true;
  let agentEmail = [];
  let fd_api_key = document.getElementById('fd-api-key');
  let fd_domain = document.getElementById('fd-domain');
  document.getElementById("primary123").style.display = "none";
  console.log('validate app');
 
  if(fd_api_key.value && fd_domain.value  && count==1 ){
    // let customObjectData = document.getElementById('customObjectData');
    let fd_fields = document.getElementById('fd_fields');
    let accessvalue = document.getElementById('accessvalue');
    // console.log('accessvalue',accessvalue);

  let addtag = document.getElementById('add-tag').value;
  let agentEmailto =  document.getElementById('agentEmailId').value;
  
      // if(customObjectData.value == ""){
      //   document.querySelector('fw-tabs').activeTabIndex = 0;
      //   isValid = false;         
      //               count=1;
      //               msg="Error! Please correct the following error(s): Please select the custom object <b>Custom Object Setting</b> tab.";
      //                     bindError(msg); 
      //        return isValid;
      // }
      // else{
      //   var realcustomobject = ["rule_id", "automation_type_id","payload"];
      //       var selectcustomobject = [];
      //            console.log(customObjectData.value);
      //          var filercustomObject =  custom_objectarr.filter(customobj=> customobj.id == customObjectData.value);
      //          for(var i=0;i<filercustomObject[0].fields.length;i++){
      //             selectcustomobject.push(filercustomObject[0].fields[i].name)
      //          }
      //         console.log(selectcustomobject);
      //         const matchcustomobject = selectcustomobject.filter(element => realcustomobject.includes(element));
      //     console.log("matchcustomobject",matchcustomobject);
      //     if(matchcustomobject.length != 3){
      //         document.querySelector('fw-tabs').activeTabIndex = 0;
      //       isValid = false;         
      //               count=1;
      //      msg="Error! Please correct the following error(s): Please select the correct custom object of fields are 'rule_id,automation_type_id,payload' <b>Custom Object Setting</b> tab.";
      //     bindError(msg);
      //     return isValid;
      //     }

      // }
   
          
        if(fd_fields.value == ""){
          document.querySelector('fw-tabs').activeTabIndex = 0;
              isValid = false;         
              count=1;
              msg="Error! Please correct the following error(s): Please select fields in the <b>App Dashboard Access</b> tab.";
                    bindError(msg); return isValid;   
        } 

        if(accessvalue.value.length == 0){
                      document.querySelector('fw-tabs').activeTabIndex = 0;
                       isValid = false;         
                       count=1;
                       msg="Error! Please correct the following error(s): Please select roles in the <b>App Dashboard Access</b> tab.";
                 bindError(msg);  return isValid;   
            }  

                for (var i = 0; i < agentEmailto.length; i++) {
                agentEmail.push(agentEmailto[i]);
                  }
                if(addtag.length != ""){
                var emails = addtag.split(',');
                  for (var i = 0; i < emails.length; i++) {
                agentEmail.push(emails[i]);
                  }
                }

                    if(agentEmail.length > 0){
                        var regex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

                          for (var i = 0; i < agentEmail.length; i++) {
                              if( agentEmail[i] === "" || !regex.test(agentEmail[i].replace(/\s/g, ""))){
                                document.querySelector('fw-tabs').activeTabIndex = 1;
                                isValid = false;
                                count=1;
                                        msg="Error! Please correct the following error(s): Please enter valid email ids in <b>Email Setting</b> tab.";
                                              bindError(msg); return isValid;
                              }
                          }
                      }else{
                        document.querySelector('fw-tabs').activeTabIndex = 1;
                           isValid = false;         
                           count=1;
                            msg="Error! Please correct the following error(s): Please add email ids in the <b>Email Setting</b> tab.";
                              bindError(msg);   return isValid;
                       } 
                    
                  
  }
  else{    
		                                                                                                                                          
		let div_pop=document.getElementById("primary12");
			//console.log("div_pop",div_pop);
			while (div_pop.childNodes.length > 0) {
					  div_pop.removeChild(div_pop.childNodes[0]);
					}
                                                                                      
			let div_primary=document.createElement("div");
			while (div_primary.childNodes.length > 0) {
					  div_primary.removeChild(div_primary.childNodes[0]);
					}
			div_primary.setAttribute("class","alert alert-danger alert-dismissible fade show");
			div_primary.setAttribute("role","alert");
			div_primary.setAttribute("style","border-top-width: 1px;top: 8px;margin-bottom: 14px;");
			let strond_tag=document.createElement("strong");
			strond_tag.innerHTML="Error! Please correct the following error(s): Please validate the App. Click on <b>Validate</b> button to validate the App.";
			let button_c=document.createElement("button");
			button_c.setAttribute("type","button");
			button_c.setAttribute("style","font-size: 14px;");
			button_c.setAttribute("class","close");
			button_c.setAttribute("data-dismiss","alert");
			button_c.setAttribute("aria-label","Close");
			let span_c=document.createElement("span");
			span_c.setAttribute("aria-hidden","true");span_c.innerHTML="&times";
			button_c.appendChild(span_c);
			strond_tag.appendChild(button_c);
			div_primary.appendChild(strond_tag);
			div_pop.appendChild(div_primary);
			
	    isValid = false;
    
  }
console.log("isValid",isValid);

  return isValid;
}

//post config 
function postConfigs() {
	console.log("postConfigs");
	
  
  let params = {     
	 __meta: {
              secure: ["api_key"]
            },
    api_key: document.getElementById('fd-api-key').value,
    domain: document.getElementById('fd-domain').value,
    // schemas_id:document.getElementById('customObjectData').value,
    accessvalue:document.getElementById('accessvalue').value,
    fd_fields:document.getElementById('fd_fields').value,
  agentEmail:document.getElementById('agentEmailId').value,
  toemail:document.getElementById('add-tag').value,
  };

  let paramsWithStoreKey = Object.assign(params);
console.log("paramsWithStoreKey",paramsWithStoreKey);
  return paramsWithStoreKey;
}

var fd_api_key,fd_domain;
setTimeout(()=>{
  
  fd_domain = document.getElementById("fd-domain");
  fd_api_key = document.getElementById("fd-api-key");
  validateInputField();

}, 1000);




function validateInputField() {


  fd_domain.addEventListener("input", (data)=>{
    if(fd_domain.value == null || fd_domain.value == ""){
      fd_domain.state = "error";
      fd_domain['state-text'] = 'Invalid code';
    }else{
      fd_domain.state = "normal";
      fd_domain['state-text'] = 'Invalid name';
    }
  }); 
  fd_api_key.addEventListener("input", (data)=>{
    if(fd_api_key.value == null || fd_api_key.value == ""){
      fd_api_key.state = "error";
      fd_api_key['state-text'] = 'Invalid code';
    }else{
      fd_api_key.state = "normal";
      fd_api_key['state-text'] = 'Invalid name';
    }
  });  
   
}

function validateAzure(event, data){
 
	 if(document.getElementById("fd-domain").value!="" && document.getElementById("fd-api-key").value!="" )
	 {
     		
     console.log("domain not equal to null");
			//Failed
				let div_pop=document.getElementById("primary12");
				while (div_pop.childNodes.length > 0) {
						  div_pop.removeChild(div_pop.childNodes[0]);
						}
						
				//ERROR BLOCK
				let div_pop1=document.getElementById("danger123");				
				while (div_pop1.childNodes.length > 0) {
						  div_pop1.removeChild(div_pop1.childNodes[0]);
						}
		validateAzureApi()
    
        .then((e)=>{
          
          
             let {status, msg} = e;
			 document.getElementById('show-validate-spin').style.display="none";
			  if(status==true){
				//successfully				
					let div_pop=document.getElementById("primary12");						
						while (div_pop.childNodes.length > 0) {
								  div_pop.removeChild(div_pop.childNodes[0]);
								}
						//ERROR BLOCK
						let div_pop1=document.getElementById("danger123");						
						while (div_pop1.childNodes.length > 0) {
								  div_pop1.removeChild(div_pop1.childNodes[0]);
								}
					
						let div_primary=document.createElement("div");
						while (div_primary.childNodes.length > 0) {
								  div_primary.removeChild(div_primary.childNodes[0]);
								}
						
						div_primary.setAttribute("class","alert alert-primary alert-dismissible fade show");
						div_primary.setAttribute("role","alert");
						div_primary.setAttribute("style","border-top-width: 1px;top: 8px;margin-bottom: 14px;");
						let strond_tag=document.createElement("strong");
						strond_tag.innerHTML="App validated successfully. Moving on next page.";
						let button_c=document.createElement("button");
						button_c.setAttribute("type","button");
						button_c.setAttribute("style","font-size: 14px;");
						button_c.setAttribute("class","close");
						button_c.setAttribute("data-dismiss","alert");
						button_c.setAttribute("aria-label","Close");
						let span_c=document.createElement("span");
						span_c.setAttribute("aria-hidden","true");span_c.innerHTML="&times";
						button_c.appendChild(span_c);
						strond_tag.appendChild(button_c);
						div_primary.appendChild(strond_tag);
						div_pop.appendChild(div_primary);
			  }
			  else{
			  
				//Failed
				let div_pop=document.getElementById("primary12");				
				while (div_pop.childNodes.length > 0) {
						  div_pop.removeChild(div_pop.childNodes[0]);
						}
						
				//ERROR BLOCK
				let div_pop1=document.getElementById("danger123");				
				while (div_pop1.childNodes.length > 0) {
						  div_pop1.removeChild(div_pop1.childNodes[0]);
						}
		
				let div_primary=document.createElement("div");
				while (div_primary.childNodes.length > 0) {
						  div_primary.removeChild(div_primary.childNodes[0]);
						}
				div_primary.setAttribute("class","alert alert-danger alert-dismissible fade show");
				div_primary.setAttribute("role","alert");
				div_primary.setAttribute("style","border-top-width: 1px;top: 8px;margin-bottom: 14px;");
				let strond_tag=document.createElement("strong");
				//..strond_tag.innerHTML="Error!Please correct the following error(s):App validation failed.DevOps URL/Token is not valid.";
				//strond_tag.innerHTML="Error! Please correct the following error(s): App validation failed. DevOps Domain Name/Token is not valid.";
				strond_tag.innerHTML=msg;
				let button_c=document.createElement("button");
				button_c.setAttribute("type","button");				
				button_c.setAttribute("style","font-size: 14px;");
				button_c.setAttribute("class","close");
				button_c.setAttribute("data-dismiss","alert");
				button_c.setAttribute("aria-label","Close");
				let span_c=document.createElement("span");
				span_c.setAttribute("aria-hidden","true");span_c.innerHTML="&times";
				button_c.appendChild(span_c);
				strond_tag.appendChild(button_c);
				div_primary.appendChild(strond_tag);
				div_pop.appendChild(div_primary);
			  }
         
        })
        .catch((err)=>{
          pop_error.innerHTML = err.msg;
          pop_error.style.display = 'block';
          exitSpinAndDisable(load_spinn, event);
        })
	
		
	 }	 
	 else if(document.getElementById("fd-domain").value=="" || document.getElementById("fd-api-key").value=="" ){
	 let message;
   var key = document.getElementById("fd-api-key");
   key.state = "normal";
   var dom = document.getElementById("fd-domain");
   dom.state = "normal";
	 let msg1=document.getElementById("fd-domain").value!=""? "":" Please enter Freshdesk Domain Name.";
	 let msg2=document.getElementById("fd-api-key").value!=""? "":" Please enter  Freshdesk API Key.";	

  message="Error! Please correct the following error(s): App validation failed."+msg1+msg2;

	 let div_pop=document.getElementById("primary12");
			while (div_pop.childNodes.length > 0) {
					  div_pop.removeChild(div_pop.childNodes[0]);
					}
			
			let div_primary=document.createElement("div");
			while (div_primary.childNodes.length > 0) {
					  div_primary.removeChild(div_primary.childNodes[0]);
					}
			div_primary.setAttribute("class","alert alert-danger alert-dismissible fade show");
			div_primary.setAttribute("role","alert");
			div_primary.setAttribute("style","border-top-width: 1px;top: 8px;margin-bottom: 14px;");
			let strond_tag=document.createElement("strong");
			strond_tag.innerHTML=message;
			let button_c=document.createElement("button");
			button_c.setAttribute("type","button");			
			button_c.setAttribute("style","font-size: 14px;");
			button_c.setAttribute("class","close");
			button_c.setAttribute("data-dismiss","alert");
			button_c.setAttribute("aria-label","Close");
			let span_c=document.createElement("span");
			span_c.setAttribute("aria-hidden","true");span_c.innerHTML="&times";
			button_c.appendChild(span_c);
			strond_tag.appendChild(button_c);
			div_primary.appendChild(strond_tag);
			div_pop.appendChild(div_primary);	 
	 
	 }

  
  
}


function exitSpinAndDisable(load_spinn, event) {
  load_spinn.style.display = 'none';
  event.disabled = false;
}
function validateFreshdeskApi(freshdeskurl,freshdesktoken){
  
document.getElementById('show-validate-spin').style.display="block";
  return new Promise(function(resolve,reject){    
    client.request.invokeTemplate("iparamValidate", {
                            context: {
                                subdomain: freshdeskurl,
                                api_key: freshdesktoken,
                            }
                        })
				.then (function(body) {
						if(body)
						{							
							// let details=JSON.parse(body.response);
              // custom_objectarr = details.schemas;
            // showCustomobject(details.schemas);
            var i=1;
            addAgent_(i,freshdeskurl,freshdesktoken);
							resolve(true);
						}
						
					}).catch(err=>{     
					  					  
					  resolve(false);  
					})  
              
  })

}

// function showCustomobject(customobject){
//   document.getElementById("primary123").style.display = "none";

//     let groups_select = document.getElementById("custom_object");
//     while (groups_select.childNodes.length > 0) {
//       groups_select.removeChild(groups_select.childNodes[0]);
// 					}
//     let multiple_select = document.createElement('fw-select');
   
//     for (var i = 0; i < customobject.length; i++) {
//       let options_elemet = document.createElement('fw-select-option');
//       options_elemet.setAttribute('value',customobject[i].id);
//       if (config && config.schemas_id) {
//                   if(customobject[i].id == config.schemas_id){
//                   console.log("selected....................");
//                   options_elemet.setAttribute('selected', 'selected');
//                   }
//         }
//                     options_elemet.innerHTML = customobject[i].name;
//               multiple_select.appendChild(options_elemet);
//     }
//     multiple_select.setAttribute('label','Custom Object');
//     multiple_select.setAttribute('id','customObjectData');
//     multiple_select.setAttribute('required','true');
//     multiple_select.setAttribute('placeholder','Select Custom Object');
//     multiple_select.setAttribute('hint-text','Select Custom Object');
//     multiple_select.setAttribute('style', '--fw-popover-max-height: 200px');
//     multiple_select.setAttribute('onclick', 'changecustomObject()');
//     groups_select.appendChild(multiple_select);
     
//     multiple_select.addEventListener('fwChange', (e)=>{ 
//       document.getElementById("primary123").style.display = "none";
//       var realcustomobject = ["rule_id", "automation_type_id","payload"];
//       var selectcustomobject = [];
//       console.log(e.detail.value);
//      var filercustomObject =  custom_objectarr.filter(customobj=> customobj.id == e.detail.value);
//     for(var i=0;i<filercustomObject[0].fields.length;i++){
//       selectcustomobject.push(filercustomObject[0].fields[i].name)
//     }
//     console.log(selectcustomobject);
//     const matchcustomobject = selectcustomobject.filter(element => realcustomobject.includes(element));
// console.log("matchcustomobject",matchcustomobject);
// if(matchcustomobject.length != 3){
// var msg="Error! Please correct the following error(s): Please select the correct custom object of fields are 'rule_id,automation_type_id,payload' <b>Custom Object Setting</b> tab.";
// bindError(msg);
// }

//       });
//   }

  function addAgent_(i,freshdeskurl,freshdesktoken){
      return new Promise(function(resolve,reject){    
        client.request.invokeTemplate("getAllAgents", {
                                context: {
                                    subdomain: freshdeskurl,
                                    api_key: freshdesktoken,
                                    page:i
                                }
                            })
            .then (function(body) {
              var agenting = JSON.parse(body.response);
                    if (agenting && agenting.length != 0){
                      agent_list_ = agent_list_.concat(agenting);  
                        i = i + 1;
                        addAgent_(i,freshdeskurl, freshdesktoken);
                        }else{
                      console.log("looping endstage agent_list",agent_list_);
                      showAllagent_(agent_list_);
                    }
                            
              }).catch(err=>{     
                            
                resolve(false);  
              })  
                  
      })
    }
    
    function showAllagent_(requiredField){
        let groups_select_ = document.getElementById("agent_prp-table");
        while (groups_select_.childNodes.length > 0) {
                    groups_select_.removeChild(groups_select_.childNodes[0]);
              }
        let multiple_select = document.createElement('fw-select');
        for (var i = 0; i < requiredField.length; i++) {
          let options_elemet = document.createElement('fw-select-option');
          options_elemet.setAttribute('value',requiredField[i].contact.email);
          if (config && config.agentEmail) {
                for (var j = 0; j < config.agentEmail.length; j++) {
                      if(requiredField[i].contact.email == config.agentEmail[j]){
                      console.log("selected....................");
                      options_elemet.setAttribute('selected', 'selected');
                      }
                }
            }
                        options_elemet.innerHTML = requiredField[i].contact.email;
                  multiple_select.appendChild(options_elemet);
        }
        multiple_select.setAttribute('label','To Email Ids');
        multiple_select.setAttribute('id','agentEmailId');
        multiple_select.setAttribute('multiple','true');
        multiple_select.setAttribute('required','true');
        multiple_select.setAttribute('placeholder','Select To Email Ids');
        multiple_select.setAttribute('hint-text','Select To Email Ids');
        multiple_select.setAttribute('style', '--fw-popover-max-height: 200px');
        groups_select_.appendChild(multiple_select);
        // console.log(groups_select_);
        multiple_select.addEventListener('fwChange', (e)=>{ 
          document.getElementById("primary123").style.display = "none";   
          });

           useWorkspace = document.getElementById("customWorkspace").value;
}

 function addRoles(freshdeskurl,freshdesktoken){
			
  console.log(freshdeskurl,freshdesktoken);
  return new Promise(function(resolve,reject){    
    client.request.invokeTemplate("getAllRoles", {
                            context: {
                                subdomain: freshdeskurl,
                                api_key: freshdesktoken,
                            }
                        })
				.then (function(body) {
						if(body)
						{							
							let details=JSON.parse(body.response);
              console.log("get roles:",details);
              showAllRoles(details);
							resolve(true);
						}
						
					}).catch(err=>{     
					  					  
					  resolve(false);  
					})  
              
  })
}

function showAllRoles(requiredField){
  console.log(requiredField);
  document.getElementById('show-customobject-spin').style.display = "none";
    let groups_select = document.getElementById("access-table");
    while (groups_select.childNodes.length > 0) {
      groups_select.removeChild(groups_select.childNodes[0]);
					}
    let multiple_select = document.createElement('fw-select');
   
    for (var i = 0; i < requiredField.length; i++) {
      let options_elemet = document.createElement('fw-select-option');
      options_elemet.setAttribute('value',requiredField[i].id);
      if (config && config.accessvalue) {
            for (var j = 0; j < config.accessvalue.length; j++) {
                  if(requiredField[i].id == config.accessvalue[j]){
                  console.log("selected....................");
                  options_elemet.setAttribute('selected', 'selected');
                  }
            }
        }
                    options_elemet.innerHTML = requiredField[i].name;
              multiple_select.appendChild(options_elemet);
    }
    multiple_select.setAttribute('label','Roles');
    multiple_select.setAttribute('id','accessvalue');
    multiple_select.setAttribute('multiple','true');
    multiple_select.setAttribute('required','true');
    multiple_select.setAttribute('placeholder','Select Roles');
    multiple_select.setAttribute('hint-text','Select Roles');
    multiple_select.setAttribute('style', '--fw-popover-max-height: 200px');
    groups_select.appendChild(multiple_select);
     
    multiple_select.addEventListener('fwChange', (e)=>{ 
      document.getElementById("primary123").style.display = "none";   
      });
  }

  function addAgent(i,freshdeskurl,freshdesktoken){
			
      console.log(freshdeskurl,freshdesktoken);
      return new Promise(function(resolve,reject){    
        client.request.invokeTemplate("getAllAgents", {
                                context: {
                                    subdomain: freshdeskurl,
                                    api_key: freshdesktoken,
                                    page:i
                                }
                            })
            .then (function(body) {
              var agenting = JSON.parse(body.response);
          console.log("grouping end stage",agenting);
         if (agenting && agenting.length != 0){
          agent_list = agent_list.concat(agenting);  
             i = i + 1;
             addAgent(i,freshdeskurl, freshdesktoken);
            }else{
          console.log("looping end stage agent_list",agent_list);
          showAllagent(agent_list);
         }
                
              }).catch(err=>{     
                            
                resolve(false);  
              })  
                  
      })
    }
    
    function showAllagent(requiredField){
      console.log(requiredField);
      document.getElementById('show-customobject-spin').style.display = "none";
        let groups_select = document.getElementById("access-table");
        while (groups_select.childNodes.length > 0) {
          groups_select.removeChild(groups_select.childNodes[0]);
              }
        let multiple_select = document.createElement('fw-select');
        for (var i = 0; i < requiredField.length; i++) {
          let options_elemet = document.createElement('fw-select-option');
          options_elemet.setAttribute('value',requiredField[i].id);
          if (config && config.accessvalue) {
                for (var j = 0; j < config.accessvalue.length; j++) {
                      if(requiredField[i].id == config.accessvalue[j]){
                      console.log("selected....................");
                      options_elemet.setAttribute('selected', 'selected');
                      }
                }
            }
                        options_elemet.innerHTML = requiredField[i].contact.name;
                  multiple_select.appendChild(options_elemet);
        }
        multiple_select.setAttribute('label','Agent');
        multiple_select.setAttribute('id','accessvalue');
        multiple_select.setAttribute('multiple','true');
        multiple_select.setAttribute('required','true');
        multiple_select.setAttribute('placeholder','Select the agent');
        multiple_select.setAttribute('hint-text','Select the agent');
        multiple_select.setAttribute('style', '--fw-popover-max-height: 200px');
        groups_select.appendChild(multiple_select);
         
        multiple_select.addEventListener('fwChange', (e)=>{ 
          document.getElementById("primary123").style.display = "none";   
          });
      }

      

function validateAzureApi()
{

document.getElementById('show-validate-spin').style.display="block";
let message;
//count =1;
		return new Promise(function(resolve, reject) {	
			//Validate Freshdesk Credentials
			let fddomain=document.getElementById("fd-domain").value;
			let fdtoken=document.getElementById("fd-api-key").value;
			validateFreshdeskApi(fddomain,fdtoken)
			.then((data)=>{			
			 if(data == true){
        console.log("FD TRUE");
			    count =1;
				message="App validated successfully. Move to next page.";resolve({status:true,msg:message});
        setTimeout(()=>{
        showLvl2();
        },1000)
			  }else{//console.log("FD FALSE");
			    count =0;
				message="Error! Please correct the following error(s): App validation failed. Freshdesk Domain Name/API Key is not valid.";resolve({status:false,msg:message});
			  }
			}) 
		 });
}

document.onreadystatechange = function () {
                        if (document.readyState === 'interactive') renderApp();
                        async function renderApp() {
                            try {
                                console.log("app initialisation function triggered");
                            let _client = await app.initialized();
                            client = _client;
                            } catch (error) {
                            return console.error(error);
                            }
                        }
     };

     
function validateBlank()
{
  count=0;

//successfully				
					let div_pop=document.getElementById("primary12");
						////console.log("div_pop",div_pop);
						while (div_pop.childNodes.length > 0) {
								  div_pop.removeChild(div_pop.childNodes[0]);
								}
						let div_pop1=document.getElementById("danger123");
						////console.log("div_pop1",div_pop1);
						while (div_pop1.childNodes.length > 0) {
								  div_pop1.removeChild(div_pop1.childNodes[0]);
								}
						let div_primary=document.createElement("div");
						while (div_primary.childNodes.length > 0) {
								  div_primary.removeChild(div_primary.childNodes[0]);
								}


}

// function changecustomObject(){
//   console.log(custom_objectarr);
//   if(custom_objectarr.length == 0){
//     var msg="Error! Please correct the following error(s): Please create custom object fields are rule_id,automation_type_id,payload.";
// bindError(msg);
//   }
// }

function  getPageingGroup(i,freshdeskurl, freshdesktoken){

  return new Promise(function (resolve, reject) {
    client.request.invokeTemplate("groupList", {
                            context: {
                                subdomain: freshdeskurl,
                                api_key: freshdesktoken,
                                page:i
                            }
                        })
				.then((group_) => {
				var grouping = JSON.parse(group_.response);
          console.log("grouping end stage",grouping);
         if (grouping && grouping.length != 0){
            group_list = group_list.concat(grouping);  
             i = i + 1;
             getPageingGroup(i,freshdeskurl, freshdesktoken);
            }else{
          console.log("looping end stage",i);
          groupoption(group_list);
         }
				}).catch((err) => {
				   reject(err);
				})
			});
}
function groupoption(grouping){
  document.getElementById('show-customobject-spin').style.display = "none";
  let groups_select = document.getElementById("access-table");
  while (groups_select.childNodes.length > 0) {
    groups_select.removeChild(groups_select.childNodes[0]);
								}
  let multiple_select = document.createElement('fw-select');
  for (var i = 0; i < grouping.length; i++) {
    let options_elemet = document.createElement('fw-select-option');
			if(config && config.accessvalue){
			for(var j=0;j<config.accessvalue.length;j++){
				if(grouping[i].id == config.accessvalue[j]){
                   options_elemet.setAttribute('selected','true');
                }
			}           
            }
			options_elemet.setAttribute('value',grouping[i].id);
            options_elemet.innerHTML = grouping[i].name;
            multiple_select.appendChild(options_elemet);
  }
  
  multiple_select.setAttribute('label','Groups');
  multiple_select.setAttribute('id','accessvalue');
  multiple_select.setAttribute('style', '--fw-popover-max-height: 200px');
  multiple_select.setAttribute('required','true');
  multiple_select.addEventListener('fwChange',groupValOnchange);
  multiple_select.setAttribute('placeholder','Select your Groups');
  multiple_select.setAttribute('hint-text','Select your Groups');
  multiple_select.setAttribute('multiple','multiple');

  groups_select.appendChild(multiple_select);


}
//Link text onchange
function groupValOnchange(){
  document.getElementById("primary123").style.display = "none";    
		 var x = document.getElementById("groupsvalue");
		 x.setAttribute('state','normal'); 
		 x.setAttribute('hint-text','Select your Groups'); 
}

 
function bindError(msg){
  document.documentElement.scrollTop = 0;
  document.getElementById("primary123").style.display = "block";
let div_pop=document.getElementById("primary123");
			console.log("div_pop",div_pop);
			while (div_pop.childNodes.length > 0) {
					  div_pop.removeChild(div_pop.childNodes[0]);
					}

			let div_primary=document.createElement("div");
			while (div_primary.childNodes.length > 0) {
					  div_primary.removeChild(div_primary.childNodes[0]);
					}
			div_primary.setAttribute("class","alert alert-danger alert-dismissible fade show");
			div_primary.setAttribute("role","alert");
			div_primary.setAttribute("style","border-top-width: 1px;top: 8px;margin-bottom: 14px;");
			let strond_tag=document.createElement("strong");
			strond_tag.innerHTML=msg;
			let button_c=document.createElement("button");
			button_c.setAttribute("type","button");
			button_c.setAttribute("style","font-size: 14px;");
			button_c.setAttribute("class","close");
			button_c.setAttribute("data-dismiss","alert");
			button_c.setAttribute("aria-label","Close");
			let span_c=document.createElement("span");
			span_c.setAttribute("aria-hidden","true");span_c.innerHTML="&times";
			button_c.appendChild(span_c);
			strond_tag.appendChild(button_c);
			div_primary.appendChild(strond_tag);
			div_pop.appendChild(div_primary);
}
  function showLvl2() {
    $("#iparams-lvl1").hide();
    $("#iparams-lvl2").show();
    if(config && config.fd_fields === "group"){
      document.getElementById('show-customobject-spin').style.display = "block";
            var i=1;
                getPageingGroup(i,config.domain,config.api_key);
        }else if(config && config.fd_fields === "agent"){
          document.getElementById('show-customobject-spin').style.display = "block";
               var i=1;
               addAgent(i,config.domain,config.api_key);
        }else if(config && config.fd_fields === "role"){
          document.getElementById('show-customobject-spin').style.display = "block";
          addRoles(config.domain,config.api_key);
        }
  
    var multiselect= document.getElementById('fd_fields');
   multiselect.addEventListener('fwChange', (e) => { 
    console.log("e.detail.value",e.detail.value);
    multiselect.state = "normal";
    group_list = [];agent_list = [];
    let fd_api_key = document.getElementById('fd-api-key').value;
        let fd_domain = document.getElementById('fd-domain').value;
        document.getElementById("primary123").style.display = "none";
        if(e.detail.value !== ""){
        document.getElementById('show-customobject-spin').style.display = "block";
        }
        if(document.getElementById('access-table')){
            let groups_select = document.getElementById("access-table");
              while (groups_select.childNodes.length > 0) {
                groups_select.removeChild(groups_select.childNodes[0]);
                    }
        }
        if(e.detail.value === "group"){
            var i=1;
                getPageingGroup(i,fd_domain,fd_api_key);
        }else if(e.detail.value === "agent"){
               var i=1;
               addAgent(i,fd_domain,fd_api_key);
        }else if(e.detail.value === "role"){
          addRoles(fd_domain,fd_api_key);
        }
   });
  }
</script>
</head>
<body>
<div id="iparams-lvl1">  
	<div class="row" style="margin-left: 10px;">
    <div class="col-md-11">
	<div class="card-body tab-content">
      <h1 class="app-title">AUTHORIZATION</h1>
                <hr>
      <div class="web-store">
            <fw-input style="width: 96%;"
            id="fd-domain" onclick="validateBlank()"
            label="Freshdesk Domain Name"
            name="fd_domain"
            state="normal"
            error-text="Enter Freshdesk Domain Name"
            hint-text="Enter Freshdesk Domain Name"
            placeholder="Ex: domain.freshdesk.com"
            required>
          </fw-input><br>
          <fw-input  style="width: 96%;"
          id="fd-api-key" onclick="validateBlank()"
          label="Freshdesk API Key"
          name="fd-api-key"
          state="normal"
          error-text="Enter Freshdesk API Key"
          hint-text="Enter Freshdesk API Key"
          placeholder="Ex: ewr34r34rdwedewrfefr34"
          required>
        </fw-input> <br> 
			
			<div class="row">
				<div class="col-md-10"></div>
				<div class="col-md-2">
					<fw-button onclick="validateAzure(this, 'create')" id="validate_button" size="small" color="primary"> Validate </fw-button>
					<div id="show-validate-spin"  style="display:none;top: 3px;margin-left: 18px;">
						<fw-spinner size="medium" color="green"></fw-spinner>
					</div>
				</div>
			</div>
				
	   <!-- <div class="col-md-6">-->
	   <div class="row"><div class="col-md-7">
		  <div class="alert-primary12" id="primary12" >
		
			</div>

			<div class="alert-danger12" id="danger123" >
			
			</div>
	    </div> </div>
      </div><!-- web-store -->   		
	</div>	

</div>
</div><!-- row -->
</div>


<div id="iparams-lvl2" style="display:none">
	<fw-tabs>
    <div class="alert-danger12" id="primary123" style="width: 55%;">
		
    </div>
    
    <!-- <fw-tab slot="tab" panel="Create">Custom Object Setting</fw-tab> -->
    <fw-tab slot="tab" panel="access">App Dashboard Access</fw-tab>
    <fw-tab slot="tab" panel="Closing">Email Setting</fw-tab>

    <fw-tab-panel name="access">
      <div class="fade-in-below mar-bot" >
        <div class="card" style="margin-top: 7px;">
          <h2 class="section-title">
          <span>
            App Dashboard Access
          </span>
          </h2>
          <b style="font-size:11px;">Select the roles to grant Dashboard access.</b>
          <br>
          <div style="width:600px;" id="reqFeild">
            <fw-select id="fd_fields"  label="Fields" placeholder="Select the Dashboard Access"  hint-text ="Select the Fields" >
              <fw-select-option value="role">Role</fw-select-option>
              <fw-select-option value="group" >Group</fw-select-option>
              <fw-select-option value="agent">Agent</fw-select-option>
            </fw-select>
        </div>
            <br><br>
            <div id="show-customobject-spin"  style="display:none;top: 3px;margin-left: 18px;">
              <fw-spinner size="medium" color="green"></fw-spinner>
            </div>
         <div id="access-table" style="width:600px;"></div>

        </div>
        </div>
    </fw-tab-panel>

    

      <fw-tab-panel name="Closing">
        <div class="fade-in-below mar-bot" >
          <div class="card" style="margin-top: 7px;">
            <h2 class="section-title">
            <span>
              Email Setting
            </span>
            </h2>
            
            <br>
            <div id="agent_prp-table" style="width:600px;"></div>
            <br>
            <label for="city"  style='font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;-webkit-font-smoothing: antialiased;font-size:12px;font-weight:500;color:12344d;margin-bottom: 0px;padding-bottom: 4px;padding-left: 2px;'>External "To Email"</label>
        <input type="text" class="form-control" name="city" id="add-tag" placeholder="Enter email Ids"  data-role="tagsinput" />
        <span id="tags-error" style="color: #778899	; font-size:12px; font-weight: 300;">Enter email Ids</span>
        <br><br>
        <div class="alert alert-primary alert-dismissible fade show" role="alert" style="border-top-width: 1px;top: 8px;margin-bottom: 14px;">
          <b style="font-size:14px;">Note: </b>
          <b style="font-size:12px;">To ensure timely communication regarding warning and error notifications, please provide the appropriate email addresses. These emails will be used to alert users in the event of API rate limit breaches or other critical issues.</b>
        </div>
          </div>
          </div>
      </fw-tab-panel>

      <!-- <fw-tab-panel name="Create">
        <div class="fade-in-below mar-bot" >
          <div class="card" style="margin-top: 7px;">
            <fw-toast-message id="type_toast2" style="margin-left: 25%;height: 1px;" type="warning"></fw-toast-message>
            <fw-toast-message id="type_toast" style="margin-left: 25%;height: 3px;" type="success" ></fw-toast-message>
            <fw-toast-message id="type_toast1" style="margin-left: 25%;height: 3px;" type="success"></fw-toast-message>

            <h2 class="section-title">
            <span>
              Custom object setting
            </span>
            </h2>
            <div id="custom_object" style="width:600px;"></div>
         
          </div>
          </div>
      </fw-tab-panel>
       -->
      
  </fw-tabs>
</div>
	
<script>
   $('#add-tag').on('beforeItemAdd', function (e) {
      document.getElementById('tags-error').style.color = '#778899';
      document.getElementById("primary123").style.display = "none";
    });

    
 </script>
</body>
</html>



how many invoke templates are there