import React from 'react';
import './SelectSubjects.css';
import {  Button, Form, Switch, Drawer, message} from 'antd';
import { FormOutlined, LoadingOutlined } from '@ant-design/icons';
import { authenticationService } from '../../_services';
import { selectorService } from '../../services/selectorService';
import DragDropContainer from './DragNDrop/ReviewContainer'
import { DndProvider } from 'react-dnd'
import { HTML5Backend } from 'react-dnd-html5-backend'
import {isEqual} from 'lodash'


let subject = [

];


class ReviewQuestions extends React.Component {
  constructor(props) {
    super(props);

  this.state = {
    currentUser: authenticationService.currentUserValue,
    classes: props.sectionState.classes ,
    module_id: props.sectionState.subject_id,
    section_id: props.sectionState.module_id,
    module: props.sectionState.module,
    subjectId: props.sectionState.subject_id,
    examId:props.sectionState.examId,
    loaded:false,
    questions:[],
    totalQuestion:0,
    detachOngoing: false,
  };
  this.stopSubmit = React.createRef(false);
  this.handleLoadQuestions = this.handleLoadQuestions.bind(this);
  this.detachQuestionCallback = this.detachQuestionCallback.bind(this);
  this.submitReviewQuestion = this.submitReviewQuestion.bind(this);
  }

  submitReviewQuestion(){
    let list={};
    let cards =[];
    const questions = this.state.questions;
    for (let index = 0; index < questions.length; index++) {
      let c = {};
      // console.log(index, questions[index], !questions[index].pmark, !questions[index].nmark); // devlog
      if ((questions[index]).pmark < 0.1 && (questions[index]).nmark < 0) {
        this.stopSubmit.current = true;
        break;
      }

      c.id = (questions[index]).value;
      c.correct_mark = (questions[index]).pmark;
      c.negative_mark =  (questions[index]).nmark;
      cards.push(c);
      }
      list.qnsMarkList = cards;

      // console.log(list,this.props.sectionState,this.props,this.state);
      if (this.stopSubmit.current) {
        message.error({content: 'Please enter valid marks for each question in the review table'});
        return 0;
      } else {
        let section_id=this.props.sectionState.sections.filter(x=>x.label===this.props.sectionState.sectionName)[0].id;
        message.loading({ content: 'Submiting Review Question...'});
        selectorService.markQuestions(section_id, list).then(data =>{
            // console.log(data);
            if(+data.status.code < 1) {
              throw "Operation Failed. Couldn't submit the questions attached.\n Check if all values were set correctly."
            }
            message.success({ content: 'Review Question Submitted!', duration: 3 });
            // this.state.loaded = false;
            setTimeout(() => {this.props.handleCancel()}, 300);
        }).catch(error => {
            console.log(error);
            message.error({ content: "Something went wrong. Please try again." });
            return 0;
        })
      }
  }

  callbackFunctionDragNDrop = (childData) => {
    // console.log("Parent recieved Selector Data: "+ JSON.stringify(childData));
    this.setState({
        questions: childData,
   });
}
detachQuestionCallback(index){
  // console.log(this.state.questions.splice(index, 1))\
  this.setState( p => ({...p, detachOngoing: true}));
  let quesJson = {};
  let question = this.state.questions[index];
  let quesId = [];
  quesId.push(question.value);
  quesJson.idList = quesId;
  let section_id=this.props.sectionState.sections.filter(x=>x.label===this.props.sectionState.sectionName)[0].id;
  message.loading({ content: 'Detaching Question...'});
  selectorService.detachQuestion(section_id, quesJson).then(data =>{
      if(+data.status.code < 0) {
        throw data.status.message[0];
      }
      let questionsL = this.state.questions;
      questionsL = questionsL.filter((_quesItem, idx) => (idx !== index));  
      this.setState({
        questions: questionsL,
      });
      message.success({ content: 'Question Detached!', duration: 3 });
      this.setState(p => ({...p, detachOngoing: false}));
  }).catch(error => {
    process.env.NODE_ENV === "development" && console.log(error);
    if(typeof error === "string" && error[0] === "0") {
      message.error(error);
      return;
    }
    message.error({ content: "Something went wrong. Please try again." });
  });
}

  componentDidMount(){
      this.handleLoadQuestions();
  }

  componentDidUpdate(prevprops){
    // console.log(this.props.sectionState.sectionName,prevprops.sectionState.sectionName,prevprops.sectionState.sectionName!==this.props.sectionState.sectionName)
    if((this.props.sectionState.sectionName)!==(prevprops.sectionState.sectionName)){
      this.handleLoadQuestions();      
    }
  }

  removeTags(str) {
    if (str === null || str === "") return "";
    else str = str.toString();
    return str.replace(/(<([^>]+)>)/gi, "");
  }

 async handleLoadQuestions(){
    let section_id=this.props.sectionState.sections.filter(x=>x.label===this.props.sectionState.sectionName)[0].id;
   await selectorService.loadReviewQuestions(section_id).then(data => {
      // console.log('Success:', data);
      const result = data.result;
      this.state.questions = [];
      const questions = result.questions===undefined?[]:result.questions;
      this.state.totalQuestion = result.total_count;

      for (let index = 0; index < questions.length; index++) {
        let c = {};
        c.label =this.removeTags((questions[index]).title);
        c.value = (questions[index]).id;
        c.index = index;
        c.pmark = (questions[index]).correct_mark;
        c.nmark =  (questions[index]).incorrect_mark;
        this.state.questions.push(c);
        }
        this.state.loaded = true;
        this.forceUpdate();
    }).catch(err => {
      message.error({
        content: "Something went wrong.. Please reload!"
      })
    });
  }




  render() {
    // console.log(this.state.questions);
    return (
      <div className='ReviewQuestionsDiv'>
        {this.state.loaded?
        <div className="ReviewQuestionsDiv">
          {/* <DndProvider backend={HTML5Backend}> */}
            <DragDropContainer  modelState ={this.state.questions} 
              parentCallback = {this.callbackFunctionDragNDrop} 
              detachOngoing={this.state.detachOngoing} 
              detachQuestionCallback = {this.detachQuestionCallback} />
          {/* </DndProvider> */}
        </div>:(
          <div className="center-flex"><LoadingOutlined style={{fontSize: 32}} spin /></div>
        )}
    </div>
    )
  };
};

export default ReviewQuestions;
