import '@things-factory/barcode-base'
import '@things-factory/notification'
import '@things-factory/system-ui'

import gql from 'graphql-tag'
import { html } from 'lit-element'

import { registerDefaultGroups } from '@operato/board/register-default-groups.js'
import { APPEND_APP_TOOL } from '@things-factory/apptool-base'
import { auth } from '@things-factory/auth-base'
import { setAuthManagementMenus } from '@things-factory/auth-ui'
import { i18next } from '@things-factory/i18n-base'
import { appendViewpart, openPopup, toggleOverlay, TOOL_POSITION, VIEWPART_POSITION } from '@things-factory/layout-base'
import { updateMenuProvider } from '@things-factory/menu-base'
import { USE_ROLE_BY_MENUS_MANAGEMENT } from '@things-factory/menu-base/client/actions/menu'
import { ADD_MORENDA } from '@things-factory/more-base'
import { ADD_REFRESH_HANDLER, ADD_SETTING } from '@things-factory/setting-base'
import { client, navigate, store, UPDATE_BASE_URL } from '@things-factory/shell'
import { ReleaseNoteNotice } from '@things-factory/system-ui/client/viewparts/release-note-notice'
import { isMobileDevice } from '@things-factory/utils'

import { UPDATE_DASHBOARD_SETTINGS } from './actions/dashboard-settings'
import { fetchBoardSettings } from './fetch-board-settings'
import dashboard from './reducers/dashboard-settings'

console.log(`
 ▄▄  ▄▄▄  ▄▄▄ ▄▄▄   ▄▄  ▄▄▄  ▄▄
▓  ▓ ▓  ▓ ▓   ▓  ▓ ▓  ▓  ▓  ▓  ▓
▓  ▓ ▓▀▀  ▓▀▀ ▓▀▀▄ ▓▀▀▓  ▓  ▓  ▓ 
▓  ▓ ▓    ▓   ▓  ▓ ▓  ▓  ▓  ▓  ▓  
 ▀▀  ▀    ▀▀▀ ▀  ▀ ▀  ▀  ▀   ▀▀ 
`)

export default function bootstrap() {
  store.addReducers({
    dashboard
  })

  /* set board-modeller group and default templates */
  registerDefaultGroups()

  /* setting app-tools */
  store.dispatch({
    type: APPEND_APP_TOOL,
    tool: {
      name: 'notification-badge',
      template: html`
        <notification-badge
          @click=${e => {
            toggleOverlay('notification', {
              backdrop: true
            })
          }}
        >
        </notification-badge>
      `,
      position: TOOL_POSITION.REAR
    }
  })

  store.dispatch({
    type: ADD_SETTING,
    setting: {
      seq: 21,
      template: html` <default-label-printer-setting-let></default-label-printer-setting-let> `
    }
  })

  appendViewpart({
    name: 'notification',
    viewpart: {
      show: false,
      hovering: 'edge',
      template: html` <notification-list style="min-width: 300px;"></notification-list> `
    },
    position: VIEWPART_POSITION.ASIDEBAR
  })

  store.dispatch({
    type: ADD_SETTING,
    setting: {
      seq: 20,
      template: html` <notification-setting-let></notification-setting-let> `
    }
  })

  store.dispatch({
    type: ADD_SETTING,
    setting: {
      seq: 30,
      template: html` <release-note-setting-let></release-note-setting-let> `
    }
  })

  store.dispatch({
    type: ADD_MORENDA,
    morenda: {
      icon: html` <mwc-icon>help</mwc-icon> `,
      name: html` <i18n-msg msgid="text.help"></i18n-msg> `,
      action: () => {
        navigate('help')
      }
    }
  })

  /* set auth management menus into more-panel */
  auth.on('profile', async ({ credential }) => {
    setAuthManagementMenus(credential)
  })

  /* 사용자가 로그인 된 경우에 setting 변경 */
  auth.on('profile', async () => {
    // fetch dashboard settings
    await loadOpaAppSettings()
  })
  /*
   * server endpoint를 설정할 수 있음. (기본은 client가 패포된 서버를 사용함.)
   */
  store.dispatch({
    type: UPDATE_BASE_URL
    // baseUrl: 'http://opaone.com'
  })

  store.dispatch(
    updateMenuProvider(async () => {
      const response = await client.query({
        query: gql`
          query {
            menus: opaMenus {
              id
              name
              children {
                id
                rank
                name
                routingType
                idField
                titleField
                resourceType
                resourceId
                resourceName
                resourceUrl
                template
              }
            }
          }
        `
      })

      return response.data.menus
    })
  )

  if (isMobileDevice()) {
    import('./apptools/dashboard-tool').then(({ DashboardTool }) => {
      var dashboardTool = new DashboardTool()
      /* menu-list page에서만 dashboard tool 이 보이도록 한다. */
      dashboardTool.whiteList = ['menu-list']

      store.dispatch({
        type: APPEND_APP_TOOL,
        tool: {
          name: 'dashboard-tool',
          template: dashboardTool,
          position: TOOL_POSITION.REAR
        }
      })
    })
  }

  store.dispatch({
    type: ADD_REFRESH_HANDLER,
    refreshHandler: loadOpaAppSettings
  })

  store.dispatch({ type: USE_ROLE_BY_MENUS_MANAGEMENT })

  if (!ReleaseNoteNotice.seen) {
    i18next.on('initialized', () =>
      setTimeout(() => {
        openPopup(html` <release-note-notice></release-note-notice> `, {
          backdrop: true,
          size: 'large',
          title: i18next.t('title.release-note')
        })
      }, 1000)
    )
  }
}

async function loadOpaAppSettings() {
  const settings = (await fetchBoardSettings()) || []

  store.dispatch({
    type: UPDATE_DASHBOARD_SETTINGS,
    settings: settings.reduce((settings, setting) => {
      settings[setting.name] = setting
      return settings
    }, {})
  })
}
