if (!window.imageMapProConfig) window.imageMapProConfig = {}

let getLastProjectIdDone = null
export function getLastProjectId(done) {
  if (window.imageMapProConfig.wp === true) {
    getLastProjectIdDone = done
    window.parent.postMessage(
      JSON.stringify({
        action: 'getLastProjectId',
      }),
      '*'
    )
  } else {
    let result = window.localStorage.imageMapProLastProjectId || '0'
    done(result)
  }
}

let getProjectsListDone = null
export function getProjectsList(done) {
  if (window.imageMapProConfig.wp === true) {
    getProjectsListDone = done
    window.parent.postMessage(
      JSON.stringify({
        action: 'getProjectsList',
      }),
      '*'
    )
  } else {
    let projectsJSON = window.localStorage.imageMapProSaves || '[]'
    try {
      const projects = JSON.parse(projectsJSON)
      const result = projects.map((project) => ({
        id: project.id,
        name: project.general.name,
        lastSaved: project.lastSaved,
      }))
      done(result)
    } catch (err) {
      console.log(err)
      done(undefined)
    }
  }
}

let getProjectDone = null
export function getProject(id, done) {
  if (window.imageMapProConfig.wp === true) {
    getProjectDone = done
    window.parent.postMessage(
      JSON.stringify({
        action: 'getProject',
        id,
      }),
      '*'
    )
  } else {
    let result = window.localStorage.imageMapProSaves || '[]'
    try {
      result = JSON.parse(result)
    } catch (err) {
      console.log(err)
      done(undefined)
    }
    done(result.filter((o) => o.id + '' === id + '')[0])
  }
}

let saveProjectDone = null
export function saveProject(data, done) {
  data.lastSaved = new Date().getTime()
  if (window.imageMapProConfig.wp === true) {
    saveProjectDone = done
    window.parent.postMessage(
      JSON.stringify({
        action: 'saveProject',
        json: JSON.stringify(data),
        name: data.general.name,
        id: data.id,
        shortcode: data.general.shortcode,
      }),
      '*'
    )
  } else {
    let projectsJSON = window.localStorage.imageMapProSaves || '[]'
    try {
      const projects = JSON.parse(projectsJSON)
      const index = projects.findIndex((o) => o.id + '' === data.id + '')
      if (index !== -1) {
        projects[index] = data
      } else {
        projects.push(data)
      }
      const result = JSON.stringify(projects)
      window.localStorage.imageMapProSaves = result
      window.localStorage.imageMapProLastProjectId = data.id
      setTimeout(() => {
        done(true)
      }, 350)
    } catch (err) {
      console.log(err)
      done(false)
    }
  }
}

let deleteProjectDone = null
export function deleteProject(id, done) {
  if (window.imageMapProConfig.wp === true) {
    deleteProjectDone = done
    window.parent.postMessage(
      JSON.stringify({
        action: 'deleteProject',
        id,
      }),
      '*'
    )
  } else {
    let projectsJSON = window.localStorage.imageMapProSaves || '[]'
    try {
      const projects = JSON.parse(projectsJSON)
      const result = projects.filter((o) => o.id + '' !== id + '')
      const resultJSON = JSON.stringify(result)
      window.localStorage.imageMapProSaves = resultJSON
      setTimeout(() => {
        done(true)
      }, 350)
    } catch (err) {
      console.log(err)
      done(false)
    }
  }
}

// Deprecated
let _getSavesDone = null
export function getSaves(done) {
  if (window.imageMapProConfig.wp === true) {
    _getSavesDone = done
    window.parent.postMessage(
      JSON.stringify({
        action: 'getSaves',
      }),
      '*'
    )
  } else {
    let result = window.localStorage.imageMapProSaves || '[]'
    try {
      result = JSON.parse(result)
    } catch (err) {
      console.log(err)
      done(undefined)
    }
    done(result)
  }
}

let _saveDone = null
export function save(data, done) {
  data.lastSaved = new Date().getTime()

  if (window.imageMapProConfig.wp === true) {
    _saveDone = done
    window.parent.postMessage(
      JSON.stringify({
        action: 'save',
        json: JSON.stringify(data),
        name: data.general.name,
        id: data.id,
        shortcode: data.general.shortcode,
      }),
      '*'
    )
  } else {
    getSaves((saves) => {
      let index = saves.findIndex((o) => o.id + '' === data.id + '')
      if (index !== -1) {
        saves[index] = data
      } else {
        saves.push(data)
      }

      window.localStorage.imageMapProSaves = JSON.stringify(saves)
      window.localStorage.imageMapProLastSave = data.id

      setTimeout(() => {
        done(true)
      }, 500)
    })
  }
}

let _deleteSaveDone = null
export function deleteSave(id, done) {
  getSaves((saves) => {
    if (window.imageMapProConfig.wp === true) {
      _deleteSaveDone = done
      window.parent.postMessage(
        JSON.stringify({
          action: 'deleteSave',
          id,
        }),
        '*'
      )
    } else {
      saves = saves.filter((o) => o.id + '' !== id + '')
      window.localStorage.imageMapProSaves = JSON.stringify(saves)
      setTimeout(() => {
        done()
      }, 500)
    }
  })
}

export function setLastSave(id) {
  if (window.imageMapProConfig.wp === true) {
    // Ajax
  } else {
    window.localStorage.imageMapProLastSave = id
  }
}

let _getLastSaveDone = null
export function getLastSave(done) {
  if (window.imageMapProConfig.wp === true) {
    _getLastSaveDone = done
    window.parent.postMessage(
      JSON.stringify({
        action: 'getLastSave',
      }),
      '*'
    )
  } else {
    if (window.localStorage.imageMapProLastSave) {
      getSaves((saves) => {
        done(saves.filter((o) => o.id + '' === window.localStorage.imageMapProLastSave + '')[0])
      })
    } else {
      done(false)
    }
  }
}

window.addEventListener('message', (e) => {
  try {
    const data = JSON.parse(e.data)

    if (data.action === 'getLastProjectId') {
      if (getLastProjectIdDone) getLastProjectIdDone(data.id)
    }
    if (data.action === 'getProjectsList') {
      if (getProjectsListDone) getProjectsListDone(data.projectsList)
    }
    if (data.action === 'getProject') {
      if (getProjectDone) getProjectDone(data.project)
    }
    if (data.action === 'saveProject') {
      if (saveProjectDone) saveProjectDone(data.result === 'success')
    }
    if (data.action === 'deleteProject') {
      if (deleteProjectDone) deleteProjectDone(data.result === 'success')
    }

    // Deprecated
    if (data.action === '_getLastSave') {
      if (_getLastSaveDone) _getLastSaveDone(data.map)
    }
    if (data.action === '_getSaves') {
      if (_getSavesDone) _getSavesDone(data.maps)
    }
    if (data.action === '_save') {
      if (_saveDone) _saveDone(data.result === 'success')
    }
    if (data.action === '_deleteSave') {
      if (_deleteSaveDone) _deleteSaveDone(data.result === 'success')
    }
  } catch (err) {}
})
