import { r as registerInstance, h, e as getElement } from './index-c04b9ed5.js';
import { S as SignalRService, s as signalRStore } from './signalR.service-c33fba50.js';
import './environment-config.service-b191f276.js';
import './auth.store-dba2c2da.js';
import './token.service-71a5d33f.js';
import './localstorage.service-4bf408c8.js';

const sparkleDiscussionQuestionsCss = "div.question{margin-bottom:5px}div.question ul{padding-left:5px}div.question li{list-style-type:none;cursor:pointer;background:#e5053a;border-radius:4px;vertical-align:middle;line-height:40px;padding-left:20px;color:#fff;margin-bottom:5px}.question h3{color:#333;padding-top:14px;margin-bottom:4px;font-size:16px}div.question li.selected{font-weight:bold;background:#9e0428}input[type='text']{width:100%;padding:12px 20px;margin:8px 0;box-sizing:border-box;border:2px solid #ccc;-webkit-transition:0.5s;transition:0.5s;outline:none}input[type='text']:focus{border:2px solid var(--ion-color-primary)}ion-item .item-native{padding-left:0px !important}ion-button.suggetion-btn{margin-left:0px !important}.graph-container{display:flex;flex-direction:row;flex-wrap:wrap;flex-direction:column}.graph-container .question-title{width:100%}.graph-container div.question{display:flex;flex-direction:column;justify-content:flex-end;flex-basis:100px}.graph-container div.question p{text-align:center}.answer-column{background-color:antiquewhite;flex:0 0 auto;text-align:center;color:#c0873c;flex-basis:100px}.toggle-mode{color:#888}.cloud{display:inline;list-style-type:none;width:400px}.cloud>div{list-style:none;display:inline;padding:20px}.cloud>div:nth-of-type(3n+1){font-size:1.25em}.cloud>div:nth-of-type(4n+3){font-size:1.5em}.cloud>div:nth-of-type(5n - 3){font-size:1em}.bar-graph-column{display:flex;align-items:flex-end}.bar-graph-questions{display:flex;align-items:flex-start}";

const SparkleDiscussionQuestions = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.allowPostToFeed = false;
    this.feedStartingText = 'My suggestions are:';
    this.isTeacherMode = false;
    this.questions = [];
    this.error = '';
    this.modelChange = '';
    this.responses = [];
    this.tempResponses = [];
    this.suggestionList = [];
    this.postToFeedTextValue = '';
  }
  componentDidLoad() { }
  resetPollData() {
    SignalRService.getInstance().callSignalR('ResetPollData', {});
  }
  selectOption(evt, question, option) {
    evt.target.parentElement.childNodes.forEach(e => e.classList.remove('selected'));
    evt.target.classList.add('selected');
    //console.log(question, option);
    SignalRService.getInstance().callSignalR('PollSubmission', {
      questionId: question.questionId,
      question: question.questionText,
      answer: option.option,
      responseType: question.questionType,
      pageUrl: window.location.href,
    });
  }
  addSuggestion(evt, question) {
    var inputVal = evt.target.parentElement.parentElement.querySelector('input[type=text]');
    if (inputVal.value == '' || !inputVal.value) {
      this.error = 'Please enter the value';
    }
    else {
      SignalRService.getInstance().callSignalR('PollSubmission', {
        questionId: question.questionId,
        question: question.questionText,
        answer: inputVal.value,
        responseType: question.questionType,
        pageUrl: window.location.href,
      });
      //   this.dataSvc.callSignalR(
      //     {
      //       questionId: question.questionId,
      //       question: question.question,
      //       answer: inputVal.value,
      //       responseType: question.responseType,
      //     },
      //     'PollSubmission',
      //     true,
      //   );
      //&& question.updateFeedText
      if (this.allowPostToFeed) {
        this.suggestionList.push({ questionId: question.questionId, question: question.questionText, answer: inputVal.value, responseType: question.questionType });
        let value = this.suggestionList
          .map(x => x.answer)
          .join(', ')
          .toString();
        this.postToFeedTextValue = this.feedStartingText + ' ' + value;
      }
    }
  }
  // async presentToast(message: string) {
  //     const toast = await this.toastCtrl.create({
  //         message: message,
  //         duration: 2000
  //     });
  //     await toast.present();
  // }
  toggleMode() {
    this.isTeacherMode = !this.isTeacherMode;
  }
  renderOptions(question) {
    if (question.questionType == 'MULTIPLE-CHOICE') {
      return (h("ul", null, question.options.map(opt => (h("li", { onClick: evt => this.selectOption(evt, question, opt) }, opt.option)))));
    }
    else if (question.questionType == 'FEEDBACK') {
      return (h("ion-item", null, h("ion-label", null, "Choose Option ", h("ion-icon", { name: "arrow-back", mode: "ios" })), h("ion-select", { id: "customAlertSelect", interface: "alert" }, h("ion-select-option", { value: "bacon" }, "Bacon"), h("ion-select-option", { value: "olives" }, "Black Olives"), h("ion-select-option", { value: "xcheese" }, "Extra Cheese"), h("ion-select-option", { value: "peppers" }, "Green Peppers"), h("ion-select-option", { value: "mushrooms" }, "Mushrooms"), h("ion-select-option", { value: "onions" }, "Onions"), h("ion-select-option", { value: "pepperoni" }, "Pepperoni"), h("ion-select-option", { value: "pineapple" }, "Pineapple"), h("ion-select-option", { value: "sausage" }, "Sausage"), h("ion-select-option", { value: "Spinach" }, "Spinach"))));
    }
    else {
      return (h("div", null, h("input", { slot: "start", type: "text", placeholder: "Type suggestion" }), h("div", null, this.error), h("ion-item", null, h("ion-button", { class: "suggetion-btn", size: "default", slot: "end", color: "primary", onClick: evt => this.addSuggestion(evt, question) }, "ADD SUGGESTION"))));
    }
  }
  renderQuestions() {
    return [
      this.questions.map(q => (h("div", { class: 'question' }, h("h3", null, q.questionText, ' ', h("span", { class: "toggle-mode", onClick: () => this.toggleMode() }, ".")), this.renderOptions(q)))),
      this.allowPostToFeed ? h("sparkle-feed-post", { assignmentName: this.postToFeedAssignmentName, textValue: this.postToFeedTextValue }) : '',
    ];
  }
  render() {
    return this.renderQuestions();
  }
  get el() { return getElement(this); }
};
SparkleDiscussionQuestions.style = sparkleDiscussionQuestionsCss;

const sparkleDiscussionResultsCss = "div.question{margin-bottom:5px}div.question ul{padding-left:5px}div.question li{list-style-type:none;cursor:pointer;background:#e5053a;border-radius:4px;vertical-align:middle;line-height:40px;padding-left:20px;color:#fff;margin-bottom:5px}.question h3{color:#333;padding-top:14px;margin-bottom:4px;font-size:16px}div.question li.selected{font-weight:bold;background:#9e0428}input[type='text']{width:100%;padding:12px 20px;margin:8px 0;box-sizing:border-box;border:2px solid #ccc;-webkit-transition:0.5s;transition:0.5s;outline:none}input[type='text']:focus{border:2px solid var(--ion-color-primary)}ion-item .item-native{padding-left:0px !important}ion-button.suggetion-btn{margin-left:0px !important}.graph-container{display:flex;flex-direction:row;flex-wrap:wrap;flex-direction:column}.graph-container .question-title{width:100%}.graph-container div.question{display:flex;flex-direction:column;justify-content:flex-end;flex-basis:100px}.graph-container div.question p{text-align:center}.answer-column{background-color:rgba(var(--ion-color-sparkle-rgb), var(--bg-alpha, 0.06));flex:0 0 auto;text-align:center;color:#c0873c;flex-basis:100px;margin-bottom:14px}.toggle-mode{color:#888}.cloud{display:inline;list-style-type:none;width:400px}.cloud>div{list-style:none;display:inline;padding:20px}.cloud>div:nth-of-type(3n+1){font-size:1.25em}.cloud>div:nth-of-type(4n+3){font-size:1.5em}.cloud>div:nth-of-type(5n - 3){font-size:1em}.bar-graph-column{display:flex;align-items:flex-end}.bar-graph-questions{display:flex;align-items:flex-start}";

const SparkleDiscussionResults = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.allowPostToFeed = false;
    this.feedStartingText = 'My suggestions are:';
    this.isTeacherMode = false;
    this.questions = [];
    this.error = '';
    this.modelChange = '';
    this.responses = [];
    this.tempResponses = [];
    this.suggestionList = [];
  }
  questionsChaged(newValue, _oldValue) {
    this.setupData(newValue);
  }
  //Any child component can liste for server events like
  gotServerUpdate(evt) {
    if (this.isTeacherMode) {
      var detail = evt.detail;
      if (detail.type == 'list') {
        detail.data.forEach(element => {
          if (element.responseType == 'TEXT') {
            this.addToWordCloud(element);
          }
          else if (element.responseType == 'MULTIPLE-CHOICE') {
            this.addToBarChart(element);
          }
        });
      }
      else if (detail.type == 'removed') {
        this.responses = [...this.tempResponses];
      }
      else {
        detail = detail.data;
        if (detail.responseType == 'TEXT') {
          this.addToWordCloud(detail);
        }
        else if (detail.responseType == 'MULTIPLE-CHOICE') {
          this.addToBarChart(detail);
        }
      }
    }
  }
  addToWordCloud(q) {
    var isExistObj = this.responses.find(x => x.question == q.question);
    if (isExistObj) {
      this.responses = this.responses.map(resp => {
        if (resp.question == q.question) {
          return q;
        }
        return resp;
      });
    }
    else {
      this.responses = [...this.responses, q];
    }
    console.log(this.responses);
  }
  addToBarChart(q) {
    var isExistObj = this.responses.find(x => x.question == q.question);
    if (isExistObj) {
      isExistObj.responses = isExistObj.responses.map(resp => {
        var correctData = q.responses.find(x => x.response == resp.response);
        if (correctData) {
          return correctData;
        }
        return resp;
      });
      isExistObj.total = q.total;
      this.responses = this.responses.map(resp => {
        if (resp.question == isExistObj.question) {
          return isExistObj;
        }
        return resp;
      });
    }
    else {
      this.responses = [...this.responses, q];
    }
  }
  componentDidLoad() {
    if (this.questions) {
      this.setupData(this.questions);
      signalRStore.onChange('connected', connected => {
        if (connected && this.isTeacherMode) {
          SignalRService.getInstance().callSignalR('GetPollSubmission', { pageUrl: window.location.href });
        }
      });
    }
  }
  setupData(questions) {
    this.setupResponseGraph(questions);
    // if (this.isTeacherMode) {
    //   SignalRService.getInstance().callSignalR('GetPollSubmission', {});
    // }
  }
  resetPollData() {
    SignalRService.getInstance().callSignalR('ResetPollData', {});
  }
  setupResponseGraph(questions) {
    this.responses = [];
    questions.forEach(q => {
      if (q.questionType == 'TEXT') {
        this.responses = [
          ...this.responses,
          {
            question: q.questionText,
            responseType: q.questionType,
            responses: [],
            total: 0,
          },
        ];
        this.tempResponses = this.responses.slice();
      }
      else if (q.questionType == 'MULTIPLE-CHOICE') {
        var answer = [];
        Object.keys(q.options).map((o) => {
          answer.push({ count: 0, response: q.options[o].option });
        });
        this.responses = [...this.responses, { question: q.questionText, responseType: q.questionType, responses: answer, total: 0 }];
        this.tempResponses = this.responses.slice();
      }
    });
    console.log(this.responses);
  }
  columnHeight(responseCount, totalResponseCount) {
    let maxScale = 100;
    let scaleUnit = 0;
    if (totalResponseCount != 0) {
      scaleUnit = maxScale / totalResponseCount;
    }
    var size = scaleUnit * responseCount;
    return { height: `${size}px` };
  }
  getRandomColorAndFontSize(count) {
    const h = Math.floor(Math.random() * 360), s = Math.floor(Math.random() * 100) + '%', l = Math.floor(Math.random() * 60) + '%';
    let fontSize = 1;
    if (count > 0) {
      fontSize = fontSize + (count - 1) * 0.25;
    }
    return { 'color': `hsl(${h},${s},${l})`, 'font-size': `${fontSize}em` };
  }
  renderResults() {
    console.log('Responsed', this.responses);
    var barResponses = this.responses.filter(x => x.responseType == 'MULTIPLE-CHOICE');
    var cloudResponses = this.responses.filter(x => x.responseType == 'TEXT');
    return [
      // <ion-button size="default" slot="end" color="primary" onClick={(evt) => this.resetPollData()} >Reset</ion-button>,
      barResponses.map((q) => (h("div", null, ' ', h("h3", { class: "line" }, q.question), h("div", { class: "graph-container" }, h("div", { class: "bar-graph-column" }, q.responses.map(r => (h("div", { class: "answer-column", style: this.columnHeight(r.count, q.total) }, r.count)))), h("div", { class: "bar-graph-questions" }, q.responses.map(r => (h("div", { class: 'question' }, h("p", null, r.response))))))))),
      cloudResponses.map(q => [
        h("p", null, h("h3", { class: "line" }, q.question)),
        h("div", { class: "cloud" }, q.responses.map(r => (h("div", { style: this.getRandomColorAndFontSize(r.count) }, r.response)))),
      ]),
    ];
  }
  render() {
    return this.renderResults();
  }
  get el() { return getElement(this); }
  static get watchers() { return {
    "questions": ["questionsChaged"]
  }; }
};
SparkleDiscussionResults.style = sparkleDiscussionResultsCss;

export { SparkleDiscussionQuestions as sparkle_discussion_questions, SparkleDiscussionResults as sparkle_discussion_results };
