import { Command } from 'ckeditor5/src/core';
import { isVideoAllowed } from "../video/utils";
import * as QMSCKEditorService from '../../common/qmsCKEditorService';
import * as QMSCKEditorConstant from '../../common/qmsCKEditorConstant';
import { toArray } from 'ckeditor5/src/utils';

export default class BrowseVideoDialogCommand extends Command {
    refresh() {
        const videoElement = this.editor.model.document.selection.getSelectedElement();
        const isVideo = videoElement && videoElement.name === 'video' || false;
        this.isEnabled = isVideoAllowed( this.editor.model ) || isVideo;
    }

    execute(options) {
      const editor = this.editor;
      const videoElement = editor.model.document.selection.getSelectedElement();
      if(videoElement)
      {
        options.src =  videoElement.getAttribute( 'src' );
        if(options.src)
        {
          options.selectedId = videoElement.getAttribute( 'src' ).split('id=')[1].split(/&(.*)/s)[0];
        }
        options.poster =  videoElement.getAttribute( 'poster' );
        options.width =  videoElement.getAttribute( 'width' );
        options.height =  videoElement.getAttribute( 'height' );
        options.id =  videoElement.getAttribute( 'id' );
      }

      QMSCKEditorService.uploadVideoNotify({...options}, editor.id);
      window[QMSCKEditorConstant.QMSCK_BROWSE_VIDEO_IS_PROCESSING] = false;
      window.addEventListener(QMSCKEditorConstant.QMSCK_BROWSE_VIDEO_RESP, (evt) => {
            if(window[QMSCKEditorConstant.QMSCK_BROWSE_VIDEO_IS_PROCESSING] || !evt.detail){
              return;
            }

            if(videoElement)
            {
              editor.model.change( writer => {
                if(evt.detail.urls.length)
                {
                  for ( const url of toArray( evt.detail.urls ) ) {
                    writer.setAttribute( 'src', url, videoElement );
                  }
                }
                if(evt.detail.id)
                {
                  writer.setAttribute( 'id', evt.detail.id, videoElement );
                }
                
                writer.setAttribute( 'poster', evt.detail.thumbnailUrl || "", videoElement );

                if(evt.detail.width)
                {
                  writer.setAttribute( 'width', evt.detail.width, videoElement );
                }
                if(evt.detail.height)
                {
                  writer.setAttribute( 'height', evt.detail.height, videoElement );
                }
              });
              return;
            }

            window[QMSCKEditorConstant.QMSCK_BROWSE_VIDEO_IS_PROCESSING] = true;
            editor.commands.get('uploadVideo').execute(evt.detail);
      }, { once: true});
    }
}
