import React, { Suspense, useState, useEffect } from 'react'
import axios from 'axios';
//import Cookies from 'js-cookie';
import Cookies from 'universal-cookie';
import {
    Redirect,
    Route,
    useLocation,
    Switch
} from 'react-router-dom'
import { CContainer, CFade } from '@coreui/react'

// routes config
import routes from '../routes'
import Sso from 'src/views/sso';

const loading = ( <
    div className = "pt-3 text-center" >
    <div className = "sk-spinner sk-spinner-pulse" > </div>
    </div>
)

const TheContent = () => {

    const sdata = { "expiration": 479, "client_address": "123.231.121.140", "protocol": "urn:oasis:names:tc:SAML:2.0:protocol", "identity_provider": "https://sso.ts.bizside.biz/idp/shibboleth", "authn_instant": "2021-08-16T11:29:41.254Z", "authncontext_class": "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport", "attributes": [ { "name": "mail", "values": [ "akira.miyata@mobilous.com" ] }  ] }
    useEffect(() => {
      setSsoSession(sdata);
    }, []);

    const [SsoSession, setSsoSession] = useState('');
    const [UserData, setUserData] = useState('');
    const [UserId, setUserId] = useState('');

    async function fetchSession() {

        // You can await here
        const result = await axios('https://fsbsso.sumasen.net/Shibboleth.sso/Session');
        if(JSON.stringify(SsoSession) !== JSON.stringify(result.data)) {
          setSsoSession(result.data);
        }
    }

    async function postUserData(data) {

      let axiosConfig = {
        headers: {
            'Content-Type': 'application/json;charset=UTF-8',
            "Access-Control-Allow-Origin": "*",
        }
      };

      const result = await axios.post('https://fsbsso.sumasen.net/csv', data, axiosConfig)
      .catch((err) => {
        console.log("AXIOS ERROR: ", err);
      });
      console.log("user data posted");
    }

    async function fetchUser() {
      //console.log(SsoSession)
      const user_email = SsoSession.attributes[0].values[0]
      //console.log(user_email);
      const company_code = "FBS";
      const key = "api"
      const pwd = "c558a56c63c44f65956adde8863ecc3558f3e55a465d4338bb2e7d2692866fd8";

      const result = await axios.get('https://fsbsso.sumasen.net/users?email=akira.miyata@mobilous.com', {
        auth: {
          username: key,
          password: pwd
        }
      }).catch((err) => {
        console.log(err);
        return false;
      });
      //console.log(result.data);
      if(JSON.stringify(UserData) !== JSON.stringify(result.data[0])) {
        setUserData(result.data[0]);
      }
      return true;
    }

    function isCSVPath(){
      const url =window.location.href;
      if(url.includes('dashboard')) {
        return true;
      }
      else {
        return false;
      }
    }

    function get_token_from_storage_or_cookie() {
        const cookies = new Cookies();
        const shib = cookies.get('_shibsession_64656661756c7468747470733a2f2f66736273736f2e73756d6173656e2e6e65742f73686962626f6c657468')
        if (shib !== undefined) {
            fetchSession().then(() => {
                if (SsoSession !== null) {
                  fetchUser().then(() => {
                    let id = Math.floor(100000 + Math.random() * 900000)
                    if(UserId === ''){
                      setUserId(id);
                    }
                    const _firstname = UserData.firstname;
                    const _lastname = UserData.lastname;
                    const _email = UserData.email;
                    const _empcode = UserData.employee_code;
                    const json_str = '[{"id": "' + UserId + '" , "firstname": "' + _firstname + '",  "lastname":"' +_lastname+ '", "email":" ' + _email + '", "empcode": "' + _empcode + '"}]';
                    if(_empcode !== null && _empcode !== undefined){
                      if(isCSVPath()){
                        postUserData(json_str);
                      }
                    }
                    return true;
                  });
                }
            });
        } else {
            return null;
        }

    }

    return (
      <main className = "c-main">
        <CContainer fluid >
        <Suspense fallback = { loading }>
        <Switch > {
            routes.map((route, idx) => {
                return route.component && (
                  <Route key = { idx }
                    path = { route.path }
                    exact = { route.exact }
                    name = { route.name }
                    render = {
                        props =>
                        get_token_from_storage_or_cookie() !== null ?
                        ( <route.component {...props} userid={UserId}/>
                        ) : ( <Redirect to = {
                                { pathname: "/sso" }
                            }
                            />
                        )
                    }
                    />
                )
            })
        }
        <Redirect
        from = "/"
        to = "/dashboard" / >
        </Switch> </Suspense >
        </CContainer> </main >
    )
}

export default React.memo(TheContent)
