/*
 * Copyright [2019] [Metamagic]
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Created by sagar on 23/1/19.
 * INFO: THIS SERVICE USED FOR SCRIPT LOADING
 */
import { Injectable } from '@angular/core';
import { LoginProvider } from '../../forms/socialmedia/login.provider';

@Injectable()
export class ScriptLoadService {

  constructor() {}

  // THIS FUNCTION IS CREATING SCRIPT TAG AND DYNAMIC LOAD SCRIPT INFO HEAD
  loadScript(loginProviderObj: LoginProvider, onload?: any): void {
    const signInJS = document.createElement('script');
    signInJS.async = true;
    signInJS.onload = onload;
    signInJS.src = loginProviderObj.url;
    if (loginProviderObj.name === 'linkedin') {
      signInJS.async = false;
      signInJS.text = ('api_key: ' + loginProviderObj.id).replace('\'', '');
    }
    if (!this.isScriptAlreadyPresent(signInJS.src)) {
      document.head.appendChild(signInJS);
    }
  }

   // THIS METHOD IS USED FOR CHEKING SCIRPT IS PRESENT IN BODY OT NOT
   isScriptAlreadyPresent(script: any): boolean {
    const scripts = document.getElementsByTagName('script');
    let isScriptLoaded: boolean;
    // tslint:disable-next-line:prefer-for-of
    for (let i = 0; i < scripts.length; i++) {
      const scriptData = scripts[i];
      if (scriptData.src === script) {
        isScriptLoaded = true;
        return isScriptLoaded;
      }
    }
    return isScriptLoaded;
  }
}
