import React from 'react';
import ReactDOM from 'react-dom';
import LoginLayer , {setLoginClientKey} from "./components/LoginLayer";
import './css/style.css'
import './css/fonts.css'

if (window.console != undefined && console.log) {
    console.log("%cGuardian Login Component", "font:4em Arial; color:#2e6ec6; font-weight: bold;");
    console.log(`%c========================== v ${VERSION} ==========================`, "font:1em Arial; color:#2e6ec6; font-weight: bold;");
}

const clientMetaName = 'guardian-ccs-client_key';
const guardianBtnClassName = 'guardian_btn';
const guardianLayerIdName = 'guardianLayer';
let guardianLayer;
let customSuccessCallback = null;

setGuardianStyle();

window.onload = function() {
    setLoginClientKey(getClientKey());
    setGuardianDialog();
    setGuardianButtons();
}

// LoginLayer 세팅
function setGuardianDialog() {
    guardianLayer = document.createElement('div');
    guardianLayer.setAttribute('id', guardianLayerIdName);
    guardianLayer.style.visibility = 'hidden';

    ReactDOM.render(
        <LoginLayer
            onClose={onLoginClose}
            onSuccess={onLoginSuccess}
        />
        ,guardianLayer
    );
    document.body.prepend(guardianLayer);
}

// css 적용
function setGuardianStyle() {
    let guardianStyleLink = document.createElement("link");
    guardianStyleLink.rel = "stylesheet"
    guardianStyleLink.type = "text/css";
    guardianStyleLink.href = `${LIBRARY_HOST}/resources/guardian.css`;
    document.head.appendChild(guardianStyleLink);
}

// 클라이언트키 추출
function getClientKey() {
    const metas = document.getElementsByTagName('meta');
    for (const meta of metas) {
        if (meta.getAttribute('name') === clientMetaName) {
            return meta.getAttribute('content');
        }
    }
}

// 가디언 버튼 세팅
function setGuardianButtons() {
    const guardianBtnList = document.getElementsByClassName(guardianBtnClassName);
    Array.from(guardianBtnList).forEach(btn => setGuardianButton(btn));
}

function setGuardianButton(btn) {
    btn.innerText = 'BSA Login';
    btn.addEventListener('click', onClick);
}

function onClick() {
    document.body.classList.toggle('overflowHidden');
    guardianLayer.classList.toggle('workingGuardianLogin');
}

function onLoginClose() {
    guardianLayer.classList.toggle('workingGuardianLogin');
    document.body.classList.toggle('overflowHidden');
}

function onLoginSuccess(extraKey) {
    if (customSuccessCallback == null) {
        parent?.onGuardianSuccess(extraKey);
    } else {
        customSuccessCallback(extraKey);
    }
}

export default class Guardian {
    setSuccessCallback = (callback) => { customSuccessCallback = callback; }
}