import { Component, Element, State, Prop, Method, h, Host } from '@stencil/core';
import { AssignmentService } from '../../services/assignment.service';
import { FeedService } from '../../services/feed.service';
import { MediaService } from '../../services/media.service';
import { TokenService } from '../../services/token.service';
import { SparkleGlobal } from '../../util';
export class SparkleFeedPost {
  // @Prop({ connect: 'ion-toast-controller' })
  // toastCtrl: HTMLIonToastControllerElement;
  componentDidLoad() {
    this.postText = this.textValue;
    if (this.ref && this.ref.innerText) {
      this.assignmentName = this.ref.innerText;
      console.log(this.assignmentName);
    }
  }
  setText(text) {
    this.postText = text;
  }
  isAuthenticated() {
    return TokenService.getInstance().isAuthenticated();
  }
  async submitPost() {
    this.postLoading = true;
    this.errorMessage = '';
    this.successMessage = '';
    //let formData = new FormData(this.el.querySelector("form")) as any;
    //var postText = this.el.getElementsByClassName("PostText")[0] as HTMLInputElement;
    var postExternalUrl = this.el.getElementsByClassName('PostExternalUrl')[0];
    var isPublic = this.el.getElementsByClassName('IsPublic')[0];
    var data = {
      PostText: this.postText,
      IsPublic: isPublic.checked,
      ExternalResourceUrl: postExternalUrl.value,
      MiniAppId: SparkleGlobal.MY_GOALS_APP_ID,
      AssignmentName: this.assignmentName,
      AssignmentData: '',
      PostTextJSON: null,
    };
    const result = await FeedService.getInstance().createPost(data);
    if (result.Succeeded) {
      this.postLoading = false;
      //show success toast
      this.successMessage = 'Posted Successfully.';
      this.postText = '';
      this.externalResourceUrl = '';
      this.uploadedImage = '';
    }
    else {
      this.postLoading = false;
      this.errorMessage = 'There is an error while posting to feed.';
    }
    if (this.assignmentName) {
      var assignmentModel = {
        AssignmentData: JSON.stringify({ text: data.PostText, url: data.ExternalResourceUrl }),
        AssignmentName: this.assignmentName,
      };
      await AssignmentService.getInstance().createAssignment(assignmentModel);
    }
  }
  async uploadImage(evt) {
    this.uploadImageLoading = true;
    var files = evt.target.files;
    let result = await MediaService.getInstance().uploadImage(files);
    if (result.Succeeded) {
      console.log(result);
      this.uploadImageLoading = false;
      this.uploadedImage = result.Data.length > 0 ? result.Data[0].FullImageUrl : '';
      this.externalResourceUrl = result.Data.length > 0 ? result.Data[0].FullImageUrl : '';
    }
    else {
      this.uploadImageLoading = false;
      this.errorMessage = 'There is an error while uploading an image.';
    }
  }
  selectFile() {
    var fileInput = this.el.querySelector('#fileInput');
    fileInput.click();
  }
  renderUserInfo() {
    let authUser = TokenService.getInstance().getAuthUserSync();
    //var tokenInfo = { Token: null, ProfileImageUrl: null };
    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"));
    }
  }
  render() {
    const userInfo = this.renderUserInfo();
    return (h(Host, null,
      h("div", { class: "assignment-name", ref: el => (this.ref = el) },
        h("slot", null)),
      h("ion-card", null,
        h("ion-item", { class: "header", lines: "full" }, userInfo),
        h("ion-card-content", null,
          h("form", null,
            h("ion-list", null,
              h("ion-item", { class: "padding" },
                h("ion-textarea", { class: "PostText", required: true, placeholder: "Post Text", name: "PostText", value: this.postText })),
              h("ion-item", { class: "padding" },
                h("ion-input", { class: "PostExternalUrl", required: true, type: "text", placeholder: "URL", name: "ExternalResourceUrl", value: this.externalResourceUrl })),
              this.uploadedImage ? (h("ion-item", { class: "ion-padding", lines: "none" },
                h("img", { class: "uploaded-image", src: this.uploadedImage }))) : (''),
              h("ion-item", { lines: "none" },
                h("input", { type: "file", id: "fileInput", onChange: evt => this.uploadImage(evt), style: { display: 'none' }, accept: "image/*" }),
                this.uploadImageLoading ? h("ion-spinner", { color: "primary" }) : '',
                h("ion-button", { slot: "start", onClick: evt => this.selectFile() },
                  h("ion-icon", { name: "add" }),
                  "Upload Image")),
              h("div", { class: "public-post-toggle" },
                h("ion-toggle", { class: "IsPublic", color: "primary", name: "IsPublic" }),
                h("div", null, "Public Post")),
              h("div", { class: "post-footer-container" },
                h("div", { class: "post-footer" },
                  h("div", null,
                    h("div", { class: "error" }, this.errorMessage),
                    h("div", { class: "success" }, this.successMessage)),
                  h("div", null, this.postLoading ? h("ion-spinner", { color: "primary" }) : ''),
                  h("ion-button", { slot: "end", size: "default", onClick: evt => this.submitPost(), disabled: this.postLoading || !this.isAuthenticated() }, "Post")))))))));
  }
  static get is() { return "sparkle-feed-post"; }
  static get originalStyleUrls() { return {
    "$": ["sparkle-feed-post.css"]
  }; }
  static get styleUrls() { return {
    "$": ["sparkle-feed-post.css"]
  }; }
  static get properties() { return {
    "assignmentName": {
      "type": "string",
      "mutable": true,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "assignment-name",
      "reflect": false
    },
    "textValue": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "text-value",
      "reflect": false
    }
  }; }
  static get states() { return {
    "postText": {},
    "errorMessage": {},
    "uploadedImage": {},
    "successMessage": {},
    "externalResourceUrl": {},
    "uploadImageLoading": {},
    "postLoading": {}
  }; }
  static get methods() { return {
    "setText": {
      "complexType": {
        "signature": "(text: any) => Promise<void>",
        "parameters": [{
            "tags": [],
            "text": ""
          }],
        "references": {},
        "return": "Promise<void>"
      },
      "docs": {
        "text": "",
        "tags": []
      }
    }
  }; }
  static get elementRef() { return "el"; }
}
