import CountriesInput, { Country } from "./countriesInput";
import { Button, Input, InputAdornment, Paper, TextField } from "@mui/material";
import SendIcon from "@mui/icons-material/Send";
import { Download, Upload } from "@mui/icons-material";
import React, { useState } from "react";
import { User } from "../../user";
import Telegram, {
  downloadFile,
  inputFile,
  sendFile,
  uploadBigFile,
} from "../../telegram/telegram";

function SignIn() {
  let [phone, setPhone] = useState("");
  let [code, setCode] = useState("");
  let [phoneCodeHash, setPhoneCodeHash] = useState("");
  let [country, setCountry] = useState({} as Country | null);
  let [user, setUser] = useState({} as User);
  let [fileDocument, setFileDocument] = useState({} as any);
  const [fileList, setFileList] = useState([]);

  let sendCode = () => {
    console.log("phone:", phone);
    Telegram.call("auth.sendCode", {
      phone_number: (country ? country.country_code : "") + phone,
      settings: {
        _: "codeSettings",
      },
    })
      .then((result: any) => {
        console.log("auth.sendCode:", result);
        setPhoneCodeHash(result.phone_code_hash);
      })
      .catch((error: any) => {
        console.log("auth.sendCode:", error);
      });
  };

  let login = () => {
    console.log("auth code:", code);
    console.log("auth hash code:", phoneCodeHash);
    Telegram.call("auth.signIn", {
      phone_number: (country ? country.country_code : "") + phone,
      phone_code_hash: phoneCodeHash,
      phone_code: code,
    })
      .then((result: any) => {
        console.log("auth.signIn:", result);
        setUser(result.user);
        SendMessage();
      })
      .catch((error: any) => {
        console.log("auth.signIn:", error);
      });
  };

  let SendMessage = () => {
    Telegram.call("messages.sendMessage", {
      peer: {
        _: "inputPeerSelf",
      },
      message: "ice",
      random_id: (10000 + Math.random() * (100000 - 10000))
        .toFixed()
        .toString(),
    })
      .then((result: any) => {
        console.log("messages.sendMessage:", result);
      })
      .catch((error: any) => {
        console.log("messages.sendMessage:", error);
      });
  };

  let uploadFile = () => {
    console.log("uploadFile:", fileList);
    // @ts-ignore
    uploadBigFile(fileList[0]?.bytes)
      .then((file) => {
        console.log("uploadFile ret:", file);
        sendFile(
          // @ts-ignore
          inputFile(file.file_id, file.total_part, fileList[0].name),
          // @ts-ignore
          fileList[0].type
        ).then((result) => {
          console.log("sendFile ret:", result);
          setFileDocument(result.updates[1].message.media);
        });
      })
      .catch((error) => {
        console.log("uploadFile error:", error);
        alert(error);
      });
  };

  let changeFile = (e: any) => {
    console.log(e.target.files);
    const reader = new FileReader();
    reader.onload = function (event) {
      if (event.target && event.target.result) {
        let bytes = event.target.result;
        console.log(bytes);
        e.target.files[0].bytes = bytes;
        setFileList(e.target.files);
      }
    };
    reader.readAsArrayBuffer(e.target.files[0]);
  };

  let download = () => {
    console.log("download:", fileDocument);
    downloadFile(fileDocument).catch((error) => {
      console.log("download error:", error);
      alert(error);
    });
  };

  return (
    <Paper
      elevation={3}
      sx={{
        padding: "150px 50px",
        position: "absolute",
        display: "flex",
        flexDirection: "column",
        justifyContent: "space-around",
        height: "40%",
        width: "40%",
      }}
    >
      <CountriesInput
        onChange={(country) => {
          console.log(country);
          setCountry(country);
        }}
      />
      <TextField
        label={"Phone Number"}
        InputProps={{
          startAdornment: (
            <InputAdornment position="start">
              {country && country.country_code
                ? "+" + country.country_code
                : ""}
            </InputAdornment>
          ),
        }}
        value={phone}
        onChange={(e) => {
          console.log(e.target.value);
          setPhone(e.target.value);
        }}
      />
      <TextField
        label={"Auth Code"}
        value={code}
        onChange={(e) => {
          console.log(e.target.value);
          setCode(e.target.value);
        }}
      />
      {phoneCodeHash === "" ? (
        <Button variant={"contained"} onClick={sendCode}>
          发送验证码
        </Button>
      ) : (
        <Button variant={"contained"} onClick={login} endIcon={<SendIcon />}>
          登录
        </Button>
      )}

      <Input type="file" onChange={changeFile} />
      <Button variant={"contained"} onClick={uploadFile} endIcon={<Upload />}>
        上传
      </Button>
      {/*<Button variant={"contained"} onClick={download} endIcon={<Download />}>*/}
      {/*  下载*/}
      {/*</Button>*/}
    </Paper>
  );
}

export default SignIn;
