import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Events } from '@ionic/angular';
import { Injectable } from '@angular/core';
import { tap } from 'rxjs/operators';
import { Router } from '@angular/router';
import { NativeStorage } from '@ionic-native/native-storage/ngx';
import { EnvService } from './env.service';
import { User } from '../models/user';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  isLoggedIn = false;
  isVerified = false;
  isReported = false;
  role: any;
  token:any;
  userInfo:any;

    constructor(
      private http: HttpClient,
      private storage: NativeStorage,
      private env: EnvService,
      private events: Events,
      private router: Router

    ) { }
    login(email: String, password: String) {
      return this.http.post(this.env.API_URL + 'auth/login',
        {email: email, password: password}
      ).pipe(
        tap(token => {
          if (token['verified'] != null) {
            this.isVerified = true;
          }
          if (token['reported'] == 1) {
            this.isReported = true;
          }
          this.storage.setItem('token', token)
          .then(
            () => {
              console.log('Token Stored');
            },
            error => console.error('Error storing item', error)
          );
          this.token = token;
          this.isLoggedIn = true;
          this.events.publish('set_role', token['role']);
          return token;
        }),
      );
    }

    login_register_fb(fb_token: String, fb_id: String) {
      return this.http.post(this.env.API_URL + 'auth/fb',
        {access_token: fb_token, social_id: fb_id + "_facebook"}
    ).pipe(
      tap(token => {
        if (token['verified'] != null) {
          this.isVerified = true;
        }
        if (token['reported'] == 1) {
          this.isReported = true;
        }
        this.storage.setItem('token', token)
        .then(
          () => {
            console.log('Token Stored');
          },
          error => console.error('Error storing item', error)
        );
        this.token = token;
        this.isLoggedIn = true;
        this.events.publish('set_role', token['role']);
        return token;
      }),
    );
    }

    login_register_googlePlus(google_token: String, google_id: String) {
      return this.http.post(this.env.API_URL + 'auth/google',
        {access_token: google_token}
    ).pipe(
      tap(token => {
        if (token['verified'] != null) {
          this.isVerified = true;
        }
        if (token['reported'] == 1) {
          this.isReported = true;
        }
        this.storage.setItem('token', token)
        .then(
          () => {
            console.log('Token Stored');
          },
          error => console.error('Error storing item', error)
        );
        this.token = token;
        this.isLoggedIn = true;
        this.events.publish('set_role', token['role']);
        return token;
      }),
    );
    }

    register(name: String, email: String, phone: Number, password: String) {
      return this.http.post(this.env.API_URL + 'auth/register',
        {name: name, email: email, phone: phone, password: password, secret: this.env.SECRET}
      )
    }
    logout() {
      const headers = new HttpHeaders({
        'Authorization': this.token["token_type"]+" "+this.token["access_token"]
      });
      return this.http.get(this.env.API_URL + 'auth/logout', { headers: headers })
      .pipe(
        tap(data => {
          this.storage.remove("token");
          this.isLoggedIn = false;
          this.isVerified = false;
          delete this.token;
          return data;
        },
        error => {
          this.storage.remove("token");
          this.isLoggedIn = false;
          this.isVerified = false;
        })
      )
    }
    user() {
      const headers = new HttpHeaders({
        'Authorization': this.token["token_type"]+" "+this.token["access_token"]
      });
      return this.http.get<User>(this.env.API_URL + 'auth/user', { headers: headers })
      .pipe(
        tap(user => {
          if (user['phone_verified_at'] != null) {
            this.isVerified = true;
          } else {
            this.isVerified = false;
          }
          if (user['reported'] == true) {
            this.isReported = true;
          } else {
            this.isReported = false;
          }
          this.events.publish('set_role', user['role_id']);
          console.log("after login:", user);
          return user;
        })
      )
    }
    getToken() {
      return this.storage.getItem('token').then(
        data => {
          this.token = data;
          if(this.token != null) {
            this.isLoggedIn=true;
            if (this.token['verified'] != null) {
              this.isVerified = true;
            }
            if (this.token['reported'] == 1) {
              this.isReported = true;
            }
          } else {
            this.isLoggedIn=false;
          }
        },
        error => {
          this.token = null;
          this.isLoggedIn=false;
        }
      );
    }
    verifyUser(phone_string: String) {
      const headers = new HttpHeaders({
        'Authorization': this.token["token_type"]+" "+this.token["access_token"]
      });
      return this.http.post(this.env.API_URL + 'auth/verify',
        { phone: phone_string }, { headers: headers });
    }

    forgot(email: String) {
      return this.http.post(this.env.API_URL + 'auth/forgot/password',
        { email: email });
    }
}
