import { HttpClient, HttpParams } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { ConfigService } from '../config.service';
import { CookiesService } from '../cookies.service';
import { NavbarComponent } from '../navbar/navbar.component';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  public logEmail: any;
  public logPassword: any;
  public remember: any;
  constructor(
    private http: HttpClient,
    private cookies: CookiesService,
    private router: Router,
    private config: ConfigService
  ) { }

  ngOnInit(): void { }

  onSubmit(): void {
    const user = {
      email: this.logEmail,
      password: encodeURIComponent(this.logPassword.toString())
    };

    console.log(user);
    console.log(this.remember);

    let params = new HttpParams().set('user', JSON.stringify(user));

    console.log(params);

    // this should use the body but has to revert back to using query strings
    this.http.get<any>(this.config.hostname + '/user/login', {
      params: params
    }).subscribe(async data => {
      console.log(JSON.stringify(data));
      if(this.remember){
        var d = new Date();
        d.setTime(d.getTime() + (7*24*60*60*1000));
        var expires = "expires="+ d.toUTCString();
        document.cookie = `proxima-login-cookie=${data['payload']['username']},${data['payload']['email']},${data['payload']['id']}; ${expires};  SameSite:none; Secure`;
        document.cookie = `proxima-login-reload=1`;
      } else {
        this.cookies.setCookie('proxima-login-cookie', `${data['payload']['username']},${data['payload']['email']},${data['payload']['id']},`);
      }
      NavbarComponent.isLoggedIn = true;
      this.router.navigate(['/profile']);
    });
  }
}