import socket from './socket/index';
import ossService from './oss/ossService';
import eventEmitter from './utils/events';
import _ from 'underscore';
import './dashboard/v1/vendor';
import { OssServiceType } from './oss/index.d';
import { SdkOptions } from './index.d';
import $ from 'jquery';
import { SocketType } from './socket/index.d';
import spDashboard, { DashboardType } from './dashboard/index';

/*
opts = {
  url: '',
  path: '/ui',
  dashboard: true|false,
  onConnect: function(a, b) {
    console.log(a,b,"======2222=====")
  },
  onDisconnect:function(a, b) {
    console.log(a,b,"=====111======")
  },
  oss: {
    type: 'oss|minio',
    tokenPath: '/oss/token',
  }
}
*/

interface SPDashboard {
  socket: SocketType;
  oss: OssServiceType;
  dashboard: DashboardType;
}

interface SPWindow extends Window {
  sp?: (opts: SdkOptions) => Promise<SPDashboard>;
  ee?: NodeJS.EventEmitter;
}

const spWindow: SPWindow = window;

spWindow.sp = async (opts: SdkOptions) => {
  spWindow.ee = eventEmitter;

  if (spWindow.ee) {
    spWindow.ee.on('loading-start', function (selector: any) {
      $(selector).prepend(
        '<div class="loader"><span class="dot"></span><span class="dot"></span><span class="dot"></span><span class="dot"></span><span class="dot"></span></div>'
      );
    });
    spWindow.ee.on('loading-end', function (selector: any) {
      $(selector).children('.loader').remove();
    });
  }

  return {
    socket: await socket(opts),
    dashboard: spDashboard({ version: 'v1' }),
    oss: ossService(opts),
  };
};
