import { Component, Element, State, Prop, Method, h, Host } from '@stencil/core';
import { EnvironmentConfigService } from '../../services';
export class SparkleFeedPost {
  // @Prop({ connect: 'ion-toast-controller' })
  // toastCtrl: HTMLIonToastControllerElement;
  componentDidLoad() {
    this.postText = this.textValue;
  }
  setText(text) {
    this.postText = text;
  }
  // async postToFeed() {
  //   const sparkleConfig: EnvironmentSparkleConfig = EnvironmentConfigService.getInstance().get('sparkle');
  //   const tocData = await AssetsService.getInstance().loadJsonFile<ICourse>(sparkleConfig.tocPath);
  //   var model = {
  //     CourseId: tocData.id,
  //     MiniAppId: SparkleGlobal.MY_GOALS_APP_ID,
  //     PostText: MyGoalTemplate(this.name.value, this.goalUpdateText.value, this.progress),
  //     PostTextJSON: MyGoalTemplateJSON(this.name.value, this.goalUpdateText.value, this.progress),
  //     IsPublic: this.public,
  //     ExternalResourceUrl: "",
  //   }
  //   const result = await FeedService.getInstance().createPost(model);
  //   if (result.Succeeded) {
  //     //show success toast
  //   }
  // }
  isAuthenticated() {
    try {
      var sparkleConfig = EnvironmentConfigService.getInstance().get('sparkle');
      if (!!sparkleConfig && !!sparkleConfig.auth && !!sparkleConfig.auth.getToken()) {
        return true;
      }
    }
    catch (_a) {
      return false;
    }
  }
  submitPost() {
    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: 1,
      AssignmentName: this.assignmentName,
      AssignmentData: '',
    };
    // this.dataSvc.saveData(data, '/api/class/feed').subscribe(
    //   x => {
    //     this.successMessage = 'Posted Successfully.';
    //     // this.presentToast('Success');
    //   },
    //   error => {
    //     this.errorMessage = 'There is an error while posting.';
    //     //  this.presentToast('There is an error');
    //   },
    // );
    //TODO can we return data from the dataSvc so we know if it's successful and can update the form? (Perhaps replace it with the post itself?)
    // if (this.assignmentName) {
    //   data.AssignmentData = JSON.stringify({ text: data.PostText, url: data.ExternalResourceUrl });
    //   this.dataSvc.saveData(data, '/api/student/assignment-response').subscribe(
    //     x => {
    //       this.successMessage = 'Posted Successfully.';
    //       // this.presentToast('Success');
    //     },
    //     error => {
    //       this.errorMessage = 'There is an error while posting.';
    //       //  this.presentToast('There is an error');
    //     },
    //   );
    // }
  }
  uploadImage(evt) {
    // this.uploadImageLoading = true;
    // var files = evt.target.files;
    // this.dataSvc.uploadImage(files, '/api/mediaitems/upload').subscribe(
    //   x => {
    //     this.uploadImageLoading = false;
    //     this.uploadedImage = x.length > 0 ? x[0].FullImageUrl : '';
    //     this.externalResourceUrl = x.length > 0 ? x[0].FullImageUrl : '';
    //     //this.successMessage = 'Posted Successfully.'
    //     // this.presentToast('Success');
    //   },
    //   error => {
    //     this.uploadImageLoading = false;
    //     this.errorMessage = 'There is an error while uploading an image.';
    //   },
    // );
  }
  selectFile() {
    var fileInput = document.getElementById('fileInput');
    fileInput.click();
  }
  renderUserInfo() {
    var tokenInfo = { Token: null, ProfileImageUrl: null };
    if (tokenInfo != null && tokenInfo.Token) {
      return (h("ion-avatar", { class: "header-avatar", slot: "end" }, tokenInfo.ProfileImageUrl ? h("img", { src: tokenInfo.ProfileImageUrl }) : h("img", { src: "/assets/img/avatar.png" })));
    }
    else {
      return (h("ion-button", { slot: "end", href: "/login" }, "Login to Post"));
    }
  }
  render() {
    const userInfo = this.renderUserInfo();
    return (h(Host, null,
      h("slot", null),
      h("ion-card", null,
        h("ion-item", { class: "header" },
          h("ion-card-title", null, "Community Wall"),
          userInfo),
        h("ion-card-content", null,
          h("form", null,
            h("ion-list", null,
              h("ion-item", { lines: "none" },
                h("ion-label", null, "Public"),
                h("ion-toggle", { class: "IsPublic", slot: "end", color: "primary", name: "IsPublic" })),
              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: "padding" },
                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("ion-item", { class: "post-footer", lines: "none" },
                h("div", null,
                  h("div", { class: "error" }, this.errorMessage),
                  h("div", { class: "success" }, this.successMessage)),
                h("ion-button", { slot: "end", size: "default", onClick: evt => this.submitPost(), disabled: !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": false,
      "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": {}
  }; }
  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"; }
}
