import {
  DeesElement,
  property,
  html,
  customElement,
  type TemplateResult,
  css,
  cssManager,
  domtools
} from '@design.estate/dees-element';

const deferred = domtools.plugins.smartpromise.defer();

declare global {
  interface HTMLElementTagNameMap {
    'dees-editormarkdown': DeesEditorMarkdown;
  }
}

@customElement('dees-editormarkdown')
export class DeesEditorMarkdown extends DeesElement {
  public static demo = () => html`<dees-editormarkdown></dees-editormarkdown>`;

  public static styles = [
    cssManager.defaultStyles,
    css`
      .gridcontainer {
        position: absolute;
        height: 100%;
        width: 100%;
        display: grid;
        grid-template-columns: 60% 40%;
      }
      .editorContainer {
        position: relative;
      }
      .outletContainer {
        background: #111;
        color: #fff;
        font-family: 'Roboto Slab';
        padding: 20px;
        overflow-y: scroll;
      }
    `,
  ];

  public render() {
    return html`
      <div class="gridcontainer">
        <div class="editorContainer">
          <dees-editor
            .language=${'markdown'}
            .content=${`# a test content

This is test content that is of longer form an hopefully starts to wrap when I need it. And yes, it does perfectly. nice.

Test | Hello
--- | ---
Yeah | So good

This is real asset I think. Why would we want to leave that on the table? Can you tell my that?

Why are we here?

Do you know?

> note:
There is something going on.

\`\`\`typescript
const hello = 'yes'
\`\`\`
`}
            wordWrap="bounded"
          ></dees-editor>
        </div>
        <div class="outletContainer">
          <dees-editormarkdownoutlet></dees-editormarkdownoutlet>
        </div>
      </div>
    `;
  }

  public async firstUpdated(_changedPropertiesArg) {
    await super.firstUpdated(_changedPropertiesArg);
    const editor = this.shadowRoot.querySelector('dees-editor');
    
    // lets care about wiring the markdown stuff.
    const markdownOutlet = this.shadowRoot.querySelector('dees-editormarkdownoutlet');
    const smartmarkdownInstance = new domtools.plugins.smartmarkdown.SmartMarkdown();
    const mdParsedResult = await smartmarkdownInstance.getMdParsedResultFromMarkdown('loading...')
    editor.contentSubject.subscribe(async contentArg => {
      await mdParsedResult.updateFromMarkdownString(contentArg)
      const html = mdParsedResult.html;
      markdownOutlet.updateHtmlText(html);
    })
  }
}