import { Component, Element, State, Prop, Listen, h, Watch } from '@stencil/core';
import { SignalRService } from '../../../services/signalR.service';
import signalRStore from '../../../stores/signalR.store';
export class SparkleDiscussionResults {
  constructor() {
    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();
  }
  static get is() { return "sparkle-discussion-results"; }
  static get originalStyleUrls() { return {
    "$": ["sparkle-discussion-results.css"]
  }; }
  static get styleUrls() { return {
    "$": ["sparkle-discussion-results.css"]
  }; }
  static get properties() { return {
    "allowPostToFeed": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "allow-post-to-feed",
      "reflect": false,
      "defaultValue": "false"
    },
    "feedStartingText": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "feed-starting-text",
      "reflect": false,
      "defaultValue": "'My suggestions are:'"
    },
    "isTeacherMode": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "is-teacher-mode",
      "reflect": false,
      "defaultValue": "false"
    },
    "questions": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Array<SparkleQuizQuestion>",
        "resolved": "SparkleQuizQuestion[]",
        "references": {
          "Array": {
            "location": "global"
          },
          "SparkleQuizQuestion": {
            "location": "import",
            "path": "../../../models/quiz.model"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "defaultValue": "[]"
    }
  }; }
  static get states() { return {
    "error": {},
    "modelChange": {},
    "responses": {},
    "suggestionList": {}
  }; }
  static get elementRef() { return "el"; }
  static get watchers() { return [{
      "propName": "questions",
      "methodName": "questionsChaged"
    }]; }
  static get listeners() { return [{
      "name": "receivedPollSubmissionSignalREvent",
      "method": "gotServerUpdate",
      "target": "body",
      "capture": false,
      "passive": false
    }]; }
}
