import { Component, Element, Prop, State, Event, Host, h, Listen } from '@stencil/core';
import { AssignmentService } from '../../services/assignment.service';
import { TokenService } from '../../services/token.service';
export class SparkleAssignment {
  constructor() {
    this.submitted = true;
    this.assignmentLoading = false;
    this.onSubmit = async (event) => {
      event.preventDefault();
      debugger;
      const formElements = event.currentTarget.querySelectorAll('sparkle-input,sparkle-file-upload');
      const formData = Array.from(formElements).reduce((acc, formElement) => {
        const { name, type, value } = formElement;
        //const name = formElement.getAttribute('name');
        let checked = false;
        if (formElement.querySelector('ion-item')) {
          checked = formElement.querySelector('ion-item').classList.contains('item-checkbox-checked');
        }
        if (name) {
          if (type === 'checkbox') {
            acc[name] = checked;
          }
          else {
            acc[name] = value;
          }
        }
        return acc;
      }, {});
      const requiredFields = Array.from(formElements).filter((formElement) => formElement.required);
      const requiredFieldsFilledIn = requiredFields.every((formElement) => formElement.value !== '');
      if (requiredFieldsFilledIn) {
        this.formSubmitted.emit(formData);
        //call api
      }
      else {
        alert('Please fill in all required fields');
      }
      this.assignmentLoading = true;
      this.errorMessage = '';
      this.successMessage = '';
      var assignmentModel = {
        AssignmentData: JSON.stringify(formData),
        AssignmentName: this.name,
      };
      console.log(assignmentModel);
      try {
        const result = await AssignmentService.getInstance().createAssignment(assignmentModel);
        if (result.Succeeded) {
          this.assignmentLoading = false;
          this.successMessage = 'Assignment submitted Successfully.';
          this.resetForm();
          //reset all inputs
        }
        else {
          this.assignmentLoading = false;
          this.errorMessage = 'There is an error while posting to feed.';
        }
      }
      catch (ex) {
        this.assignmentLoading = false;
      }
    };
  }
  fileUploaded(e) {
    console.log('fileUploaded', e);
  }
  resetForm() {
    const form = this.el.querySelector('form');
    if (form) {
      form.reset();
    }
  }
  renderUserInfo() {
    let authUser = TokenService.getInstance().getAuthUserSync();
    if (authUser && authUser.JWToken) {
      return (h("ion-avatar", { class: "header-avatar", slot: "end" }, authUser.PhotoUrl ? h("img", { src: authUser.PhotoUrl }) : h("img", { src: "/assets/img/user.png" })));
    }
    else {
      return (h("ion-button", { slot: "end", href: "/login" }, "Login to Post"));
    }
  }
  isAuthenticated() {
    return TokenService.getInstance().isAuthenticated();
  }
  render() {
    const userInfo = this.renderUserInfo();
    return (h(Host, null,
      h("ion-card", null,
        h("ion-item", { class: "header ion-justify-content-between", lines: "full" },
          h("ion-label", null, this.name),
          userInfo),
        h("ion-card-content", null,
          h("form", { onSubmit: this.onSubmit },
            h("slot", null),
            h("div", { class: "assignment-footer-container" },
              h("div", { class: "assignment-footer" },
                h("div", null,
                  h("div", { class: "error" }, this.errorMessage),
                  h("div", { class: "success" }, this.successMessage)),
                h("div", null, this.assignmentLoading ? h("ion-spinner", { color: "primary" }) : ''),
                h("ion-button", { type: "submit", slot: "end", size: "default", disabled: this.assignmentLoading || !this.isAuthenticated() }, "Submit"))))))));
  }
  static get is() { return "sparkle-assignment"; }
  static get originalStyleUrls() { return {
    "$": ["sparkle-assignment.scss"]
  }; }
  static get styleUrls() { return {
    "$": ["sparkle-assignment.css"]
  }; }
  static get properties() { return {
    "name": {
      "type": "string",
      "mutable": true,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "name",
      "reflect": false
    }
  }; }
  static get states() { return {
    "submitted": {},
    "assignmentLoading": {},
    "errorMessage": {},
    "successMessage": {}
  }; }
  static get events() { return [{
      "method": "formSubmitted",
      "name": "formSubmitted",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      }
    }]; }
  static get elementRef() { return "el"; }
  static get listeners() { return [{
      "name": "fileUploaded",
      "method": "fileUploaded",
      "target": undefined,
      "capture": false,
      "passive": false
    }]; }
}
