import { Api } from "./Api";
import { Utils } from "./Utils";

export class UtilInput {
  parent: HTMLElement;
  type: string;
  label: string;
  value: string;
  input: HTMLInputElement;
  item: any;
  key: string;
  group: HTMLElement;
  constructor(
    parent: HTMLElement,
    item: any,
    key: string,
    type = "text",
    label = "Label"
  ) {
    this.parent = parent;
    this.type = type;
    this.label = label;
    this.item = item;
    this.key = key;
    this.value = item[key];
    this.group = this.createGroup();
    this.input = this.createInput();
    this.configure();
  }
  configure() {
    const label = Utils.createLabel(this.label);
    this.label && this.group.appendChild(label);
    this.group.appendChild(this.input);
    this.parent.appendChild(this.group);
  }
  setPlaceholder(placeholder: string) {
    this.input.placeholder = placeholder;
  }
  get isCheck() {
    return this.type === "checkbox";
  }
  get isFile() {
    return this.type === "file";
  }
  createGroup() {
    const group = Utils.formGroup();
    if (this.isCheck) group.classList.add("form-check");
    return group;
  }
  createInput() {
    const input = document.createElement("input");
    input.type = this.type;
    if (!this.isFile) input.value = this.value;
    input.classList.add("form-control");
    input.oninput = () => {
      this.value = input.value;
      this.item[this.key] = this.value;
    };
    if (this.isFile) {
      this.handleFileInput(input);
      const div = Utils.formGroup();
      if (this.value) {
        Utils.createPlayer(div, this.value);
        this.parent.appendChild(div);

      }
    }
    return input;
  }

  handleFileInput(input: HTMLInputElement) {
    input.onchange = (e) => {
      const file = (e.target as HTMLInputElement).files?.[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = () => {
          this.value = reader.result as string;
          const api = new Api();
          const formData = new FormData();
          formData.append("file", file);
          formData.append(
            "name",
            `tybo.${file.name.split(".")[file.name.split(".").length - 1]}`
          );
          api.uploadFile(formData, this.item, this.key);
        };
        reader.readAsDataURL(file);
      }
    };
  }
}
