const STORYBOOK_PREVIEW = '#storybook-preview-iframe'
const FULLSCREEN = '.css-18i2ql3 > .css-1fczlqe > .css-ha8kg'
const CONSOLE = '#storybook-panel-root'
const CONTAINER = '#story-root'
const TOP_DIV = '.css-10ro1m'

Cypress.Commands.add('loadStorybook', path => {
  cy.clearCookies()
  cy.visit('/')
  cy.url().should('include', 'localhost:9001')
})

Cypress.Commands.add('loadComponent', (context, component) => {
  cy.visit('/?path=/story/' + context + '--' + component)

  var alert = '#' + context
  var warning = '#' + context + '--' + component

  if (cy.get(warning)) {
    cy.get(warning).click()
  } else {
    cy.get(alert).click()
    cy.get(warning).click()
  }

  cy.url().should('include', context)
  cy.url().should('include', component)
})

Cypress.Commands.add('snapshotComponent', type => {
  cy.get(FULLSCREEN).click()
  cy.get(TOP_DIV).invoke('css', 'top', '0px')
  cy.snapshotComponent(STORYBOOK_PREVIEW, CONTAINER + '>' + type)
})

Cypress.Commands.add(
  'clickCheckContentComponent',
  (type, sub_type, name, inner_text, method) => {
    var element = CONTAINER + '>' + type
    var sub_element = element + '>' + sub_type
    cy.iframe(STORYBOOK_PREVIEW, function (page) {
      cy.contain(CONTAINER, inner_text, page)
      cy.iget(page, element).should('have.attr', 'type', name)
      cy.iget(page, sub_element).should('be.visible')
      cy.iget(page, sub_element).should('have.attr', 'type', name)
      cy.iget(page, sub_element).click()
    })
    cy.contain(CONSOLE, method)
  }
)

Cypress.Commands.add('checkComponent', (type, name, inner_text) => {
  var element = CONTAINER + '>' + type
  cy.iframe(STORYBOOK_PREVIEW, function (page) {
    cy.contain(CONTAINER, inner_text, page)
    cy.iget(page, element).should('have.attr', 'type', name)
  })
})

Cypress.Commands.add('clickCheckComponent', (type, inner_text, method) => {
  var element = CONTAINER + '>' + type
  cy.iframe(STORYBOOK_PREVIEW, function (page) {
    cy.contain(CONTAINER, inner_text, page)
    cy.iget(page, element).should('not.be.disabled')
    cy.iget(page, element).click()
  })
  cy.contain(CONSOLE, method)
})

Cypress.Commands.add('disabledComponent', (type, inner_text) => {
  var element = CONTAINER + '>' + type
  cy.iframe(STORYBOOK_PREVIEW, function (page) {
    cy.contain(CONTAINER, inner_text, page)
    cy.iget(page, element).should('be.disabled')
  })
})

Cypress.Commands.add('clickComponent', (type, method) => {
  var element = CONTAINER + '>' + type
  cy.iframe(STORYBOOK_PREVIEW, function (page) {
    cy.iget(page, element).should('not.be.disabled')
    cy.iget(page, element).click()
  })
  cy.contain(CONSOLE, method)
})
