import React, { useEffect , useState } from "react";
import Meditor from "./m_editor";
import "./index.css";
import { returnbar } from 'educoder';
import FileLanguage from '../Component/FileLanguage';
import FP from '../Component/FileName/index';


function Index(props){
  const [ filename , setFileName ] = useState("");
  const [ language , setLanguage ] = useState("");
  const [ checkName , setCheckName ] = useState(false);
  const [ empty , setEmpty ] = useState(false);

  const {projectDetail} = props;
  const { pathname } = props && props.location;
  const urlroot = pathname.split("newfile/")[1];
  const file_path = urlroot ? `/${urlroot}/` :"/";

  useEffect(()=>{
    updateDocumentTitle();
  },[projectDetail])


  // 更新网页标题
  function updateDocumentTitle(){
    if(projectDetail && document.title.indexOf('新建文件-') === -1){
      const { author, name } = projectDetail;
      document.title = `新建文件-${author.name}/${name}`;
    }
  }


  function select_language(e){
    setLanguage(e);
  }

  function onChangeFile(value){
    setFileName(value);
    if(value){
      setEmpty(false);
    }else{
      setEmpty(true);
    }
  }

  return(
    <React.Fragment>
      <div className="main">
        <p className="pb15 bor-bottom-greyE font-16 color-grey-3 mb20">
          新建文件
        </p>
        <div>
          <div className="grid-item mb30">
            <div className="grid-item">
              <FP 
                addonBefore={`${ projectDetail && projectDetail.identifier }${returnbar(file_path)}`}
                onChangeFile={onChangeFile}
                empty={empty}
                onEmpty={(e)=>setEmpty(e)}
              />
            </div>
            <div  className="text-right">
              <FileLanguage  language={language} select_language={select_language}></FileLanguage>
            </div>
          </div>
          <div className="editorBorder">
            <Meditor
              {...props}
              filepath={`${file_path}`}
              language = {language}
              content={""}
              readOnly={false}
              editor_type="new"
              descName={filename ? `Add ${filename}`:""}
              checkName={checkName}
              onEmpty={(e)=>setEmpty(e)}
              empty={empty}
              filename={filename}
            ></Meditor>
          </div>
        </div>
      </div>
    </React.Fragment>
  )
}
export default Index;