import React, {useMemo} from 'react';
import Button from '../custom-button';
import {Dialog, DialogContent, DialogContentText} from '@material-ui/core';

import './dialog.scss';
import { useGlobalState } from '../../containers/root-container';
import {roomStore, windowMonitor} from '../../stores/room';
import {globalStore} from '../../stores/global';
import { useHistory } from 'react-router-dom';
import { RoomMessage } from '../../utils/agora-rtm-client';
import { goHome} from "../../services/agora-end-points";

interface RoomProps {
  onConfirm: (type: string) => void
  onClose: (type: string) => void
  desc: string
  type: string
}

function RoomDialog(
{
  onConfirm,
  onClose,
  desc,
  type
}: RoomProps) {

  const handleClose = () => {
    onClose(type)
  };

  const handleConfirm = () => {
    onConfirm(type)
  }

  return (
    <div>
      <Dialog
        disableBackdropClick
        open={true}
        onClose={handleClose}
        aria-labelledby="alert-dialog-title"
        aria-describedby="alert-dialog-description"
      >
        <DialogContent
          className="modal-container"
        >
          <DialogContentText className="dialog-title">
            {desc}
          </DialogContentText>
          <div className="button-group">
            <Button name="Confirm" className="confirm" onClick={handleConfirm} color="primary" />
            <Button name="Cancel" className="cancel" onClick={handleClose} color="primary" />
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}

const DialogContainer = () => {

  const history = useHistory();
  const {dialog} = useGlobalState();

  const visible = useMemo(() => {
    if (!dialog.type) return false;
    return true;
  }, [dialog]);

  const onClose = (type: string) => {
    if (type === 'closeDialog') {
      globalStore.removeDialog();
    } else if (type === 'exitRoom') {
      globalStore.removeDialog();
    }
    else if (type === 'apply') {
      roomStore.rtmClient.sendPeerMessage(
        `${roomStore.applyUid}`, {cmd: RoomMessage.rejectCoVideo}
      ).then(() => {
        globalStore.removeDialog();
      }).catch(console.warn);
    }
  }

  const onConfirm = (type: string) => {
    if (type === 'closeDialog') {
      globalStore.removeDialog();
    } else if (type === 'exitRoom') {

      // const data = roomStore.getUserUsage();
      // const host = getApiServerHost();
      // var blob = new Blob([JSON.stringify(data)], {
      //   type: 'application/x-www-form-urlencoded'
      // });
      // navigator.sendBeacon(`${host}/api/classroom/finish`, blob);
      windowMonitor.leave()
      globalStore.showLoading();
      roomStore.exitAll().then(() => {
        globalStore.stopLoading();
        globalStore.removeDialog();
        // history.push('/');
        goHome(history)
      })

    }
    else if (type === 'apply') {
      Promise.all([
        roomStore.rtmClient.sendPeerMessage(
          `${roomStore.applyUid}`, {cmd: RoomMessage.acceptCoVideo}
        ),
        roomStore.updateCourseLinkUid(roomStore.applyUid)
      ]).then(() => {
        console.log("applyUid");
        globalStore.removeNotice();
        globalStore.removeDialog();
      }).catch(console.warn);
    }

    return;
  }

  return (
    visible ?
      <RoomDialog
        type={dialog.type}
        desc={dialog.message}
        onClose={onClose}
        onConfirm={onConfirm}
      /> :
      null
  )
}


export default React.memo(DialogContainer);
