import IUser from '@/models/IUser'
import couchService from '@/services/CouchService'
import IResponse from '@/models/IResponse'

class UserService {
  public async signup(user: IUser, password: string): Promise<IResponse> {
    try {
      const response = await couchService.remote.signUp(user.userId, password, {
        metadata: user
      })
      if (response.ok) {
        const login: IResponse = await this.login(user.userId, password)
        return login
      }
      return {
        ok: response.ok
      }
    } catch (error) {
      return {
        ok: false,
        message: error.name
      }
    }
  }

  public async login(userId: string, password: string): Promise<IResponse> {
    try {
      const response = await couchService.remote.logIn(userId, password)
      return {
        ok: response.ok
      }
    } catch (error) {
      return {
        ok: false,
        message: error.name
      }
    }
  }

  /**
   * purge
   */
  public async purge(): Promise<void> {
    await couchService.purgeDb()
  }

  public async logout(): Promise<IResponse> {
    try {
      const { ok } = await couchService.remote.logOut()
      return {
        ok
      }
    } catch (error) {
      return {
        ok: false,
        message: error.name
      }
    }
  }

  public async deleteUser(userId: string): Promise<IResponse> {
    try {
      const { ok } = await couchService.remote.deleteUser(userId)
      return {
        ok
      }
    } catch (error) {
      return {
        ok: false
      }
    }
  }

  public async getUser(current: IUser | null): Promise<IUser | null> {
    try {
      const session = await couchService.remote.getSession()
      if (session.ok && session.userCtx && session.userCtx.name) {
        if (current && session.userCtx.name === current.userId) {
          return current
        }
        const user: any = await couchService.remote.getUser(
          session.userCtx.name
        )
        return user as IUser
      }
    } catch (error) {
      // tslint:disable-next-line:no-console
      console.warn({ error })
    }
    return null
  }

  public async updateUser(user: IUser): Promise<boolean> {
    try {
      const result = await couchService.remote.putUser(user.userId, {
        metadata: user
      })
      return result.ok
    } catch (error) {
      // tslint:disable-next-line:no-console
      console.warn({ error })
    }
    return false
  }

  public async hasAnonymousData(): Promise<boolean> {
    return await couchService.hasLocaleDoc()
  }
}

export default new UserService()
