import { Injectable, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { JwtSigninResponse } from '../model/jwt-signin-response.model';

import { CookieService } from 'ngx-cookie-service';
import { API_BASE_URL } from 'src/modules/common/type/injection-token.type';
import { SignupRequest } from '../model/auth-signup-request.model';

@Injectable({ providedIn: 'root' })
export class AuthService {
  public constructor(
    private httpClient: HttpClient,
    private cookieService: CookieService,
    @Inject(API_BASE_URL) private apiBaseUrl: string
  ) {}

  public signup(signupInfo: SignupRequest): Observable<any> {
    const ll = JSON.stringify(signupInfo);
    const username = signupInfo.username;
    const password = signupInfo.password;
    const email = signupInfo.email;
    const phone = signupInfo.phone;
    const descriptions = signupInfo.descriptions;
    const nickname = signupInfo.nickname;

    return this.httpClient
      .post<any>(`${this.apiBaseUrl}/auth/signup`, {
        username,
        nickname,
        email,
        password,
        descriptions,
        phone
      })
      .pipe(
        map(res => {
          console.log('signup response: ' + res);
          return res;
        })
      );
  }
  public authenticate(
    username: string,
    password: string
  ): Observable<JwtSigninResponse> {
    const model = {
      username,
      password
    };

    return this.httpClient
      .post<JwtSigninResponse>(`${this.apiBaseUrl}/auth/signin`, {
        username,
        password
      })
      .pipe(
        map(res => {
          sessionStorage.setItem('username', username);
          let tokenStr = res.tokenType + ' ' + res.accessToken;
          sessionStorage.setItem('token', tokenStr);
          return res;
        })
      );
    // return this.httpClient.post<User>(`${this.apiBaseUrl}/auth/signin`, model);
  }

  isLoggedIn() {
    const user = sessionStorage.getItem('username');
    return !(null === user);
  }

  logOut() {
    sessionStorage.removeItem('username');
  }
}
