import React, {useEffect, useState} from 'react';
import {useDispatch, useSelector} from "react-redux";
import {getDBSwitchStatus, switchDB} from "../httpServices/httpServiceDb";

const SwitchDbButton = () => {
    const {dbSwitch, dbLoading, dbError} = useSelector(state => state.dbSwitch)
    const [status, setStatus] = useState(false)
    const [btnStatus, setBtnStatus] = useState(false)
    const dispatch = useDispatch();

    useEffect(()=>{
        dispatch(getDBSwitchStatus())
    },[dispatch])

    useEffect(()=>{
        if (!dbLoading){
            if (parseInt(dbSwitch.dbSwitch) === 1){
                setStatus(true)
            }else{
                setStatus(false)
            }

            if (btnStatus){
                const dbStatus = status ? "Switched back to main database" : "Switched to archive database"
                //alertSuccess(dbStatus)
                setBtnStatus(false)
            }
        }
    },[dbSwitch, dbLoading, setStatus, btnStatus, status, setBtnStatus])

    const btnHandler = (event) =>{
        dispatch(switchDB({'db_switch': status ? 0 : 1}))
        setBtnStatus(true)
    }

    return (
        <div className="mb-[15px]">
            <a onClick={btnHandler} href="javaScript:void(0)" className="flex w-full justify-center rounded bg-primary p-3 font-medium text-gray hover:bg-opacity-90 hover:bg-blue-700 hover:text-white focus:text-white">
                {status ? "Switch back to main":"Switch to Archive"}
            </a>
        </div>
    );
};

export default SwitchDbButton;