import { defineStore } from 'pinia'
import { ConcernementsStore as concrnmtStore } from '@/stores/concernements'

import REST from '@api/rest-axios'
import JSONAPI from '@api/json-axios'
import qs from 'querystring-es3'

import { print } from 'graphql/language/printer'
import gql from 'graphql-tag'
import GQL from '@api/graphql-axios'

export const UserStore = defineStore({
  id: 'user',
  state: () => ({
    isloggedin: false,
    csrf_token: null,
    logout_token: null,
    uid: 0,
    uuid: 0,
    mail: '',
    name: null,
    roles: [],
    isAdmin: false,
    logginMessage: null
  }),
  getters: {
    
  },
  actions: {
    checkUser () {
      JSONAPI.get('').then(({ data }) => {
        console.log('checkuser jsonapi', data)
        if (data.meta && data.meta.links.me) {
          JSONAPI.get(data.meta.links.me.href).then(({ data : { data } }) => {
            console.log('checkuser jsonapi get user', data)
            this.uid = data.attributes.drupal_internal__uid
            this.mail = data.attributes.mail
            this.name = data.attributes.name
            this.isloggedin = true //data.attributes.status
            console.log('user store checkuser isloggedin', this.isloggedin);

            this.userGetRoles()
              .then(({ data : { data  : { user } } }) => {
                console.log('graphql user loaded', user)
                this.roles = user.roles
                this.checkIsAdmin()
              })
              .catch(error => {
                console.warn('Issue with graphql user loading', error)
                Promise.reject(error)
              })
          })
        }
      })
    },
    userLogin (credentials) {
      console.log('user store userLogin', credentials);
      return new Promise((resolve, reject) => {
        this.getToken(credentials)
          .then((response) => {
            console.log('userLogin getToken response', response)

            if (response.status === 200) {
              this.uid = response.data.current_user.uid
              // state.username = data.username;
              this.mail = response.data.current_user.mail
              this.csrf_token = response.data.csrf_token
              // this.isloggedin = true
              this.logout_token = response.data.logout_token
              this.getUser().then(userdata => {
                console.log('User Loggedin')
                // todo reload concernements
                // concrnmtStore().reloadConcernements(); // INFO would be good but to much complicated for now, just reload the page
                window.location.reload(); 
                resolve()
              })
            } else {
              this.loginMessage = response.data.message
              console.warn('Issue with getToken', response)
              console.log('user loggein failed', this.loginMessage)
              Promise.reject(new Error('user loggin failed'))
            }
          })
          .catch(error => {
            console.warn('Issue with Dispatch getToken', error)
            Promise.reject(error)
          })
      })
    },
    getToken (credentials) {
      console.log('userStore getToken', credentials)
      return REST.post('/user/login?_format=json',
        credentials,
        {
          validateStatus: function (status) {
            return status >= 200 && status < 500
          }
        })
    },
    getUser () {
      console.log('user store getUser');
      return new Promise((resolve, reject) => {
        REST.get('/session/token').then(({ data }) => {
          console.log('csrf_token', data)
          this.csrf_token = data
          console.log('state csrf_token', this.csrf_token)
          const params = {
            token: this.csrf_token
          }
          REST.get(`/user/${this.uid}?_format=json`, params)
            .then(({ data }) => {
              console.log('user REST getUser data', data)
              console.log('roles', data.roles)
              // with session_limit, only here we are certain that the user is logged
              // this.user = data
              // this.mail = data.mail[0].value
              this.uuid = data.uuid[0].value
              this.name = data.name[0].value
              // with session_limit, only here we are certain that the user is logged
              this.isloggedin = true
              
              // console.log('customer_profiles', data.customer_profiles.length)
              // if (data.customer_profiles.length) {
              //   dispatch('getUserProfiles', data.customer_profiles[data.customer_profiles.length - 1].target_id)
              // }

              this.userGetRoles()
                .then(({ data : { data  : { user } } }) => {
                  console.log('graphql user loaded', user)
                  this.roles = user.roles
                  this.checkIsAdmin()
                  resolve()
                })
                .catch(error => {
                  console.warn('Issue with graphql user loading', error)
                  Promise.reject(error)
                })
            })
            .catch(error => {
              console.warn('Issue with getUser', error)
              Promise.reject(error)
            })
        })
      })
    },
    userGetRoles () {
      // GRAPHQL USER QUERY (needed to get roles)
      // https://stackoverflow.com/a/55401805
      const body = {
        query: `
          query User($id: Int!){
            user(id: $id) {
              id
              roles
              username
            }
          }`,
        variables: { id: parseInt(this.uid) }
      } 

      return GQL.post('', body)
    },
    checkIsAdmin () {
      const adminroles = ['root', 'admin', 'group_admin']
      for (let r = 0; r < this.roles.length; r++) {
        if (adminroles.indexOf(this.roles[r]) !== -1) {
          this.isAdmin = true;
          break;
        }
      }
    },
    userLogout () {
      const credentials = qs.stringify({
        token: this.csrf_token
      })
      return new Promise((resolve, reject) => {
        REST.post('/user/logout', credentials)
          .then(resp => {
            console.log('userStore userLogout resp', resp)
            this.isloggedin = false
            this.roles = []
            // window.location.reload(true) ???
            // todo reload concernements
            // concrnmtStore().reloadConcernements(); // INFO would be good but to much complicated for now, just reload the page 
            window.location.reload();
            resolve()
          })
          .catch(error => {
            console.warn('Issue with logout', error)
            Promise.reject(error)
          })
      })
    }
  }
})