import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Router } from "@angular/router";
import { environment } from "src/environments/environment";
import { CommonService } from "./common.service";
import { of } from "rxjs";
import { LoginModel, SSOLoginModel } from "../models/common-model/Sign-in.model";
import { API } from "./api.service";
import { securityFunctions } from "../common/security";
import { CommonFunctionService } from "../common/common-function.service";
import * as moment from "moment";

@Injectable()
export class SSOService {
  sso: SSOLoginModel = new SSOLoginModel();
  constructor(private http: HttpClient, private router: Router, private apiServ: API, private commonService: CommonFunctionService) { }
  validateSSOLogin(key, loginUserId?) {
    sessionStorage.removeItem('LoginUserData');
    this.http.get("https://pro.ip-api.com/json/?fields=query,countryCode,lat,lon,city,proxy&&key=JZDsrdeBzIM0yyN").subscribe(data => {
      if (data) {
        let obj = {
          city: data['city'],
          countryCode: data['countryCode'],
          lat: data['lat'],
          lon: data['lon'],
          proxy: data['proxy'],
          iP: data['query'],
        };
        sessionStorage.setItem('IP', JSON.stringify(obj));
        let loginModel = new LoginModel();
        if (key) {
          let req_obj = {
            key: encodeURIComponent(key),
            city: obj.city,
            countryCode: obj.countryCode,
            lat: obj.lat,
            lon: obj.lon,
            proxy: obj.proxy,
            iP: obj.iP,
          };
          this.apiServ.AdminPost('/KeyGenerate/VendorSSOKey', req_obj).subscribe({
            next: res => {
              if (res && res.resp) {
                let data = null;
                if (loginUserId) {
                  if (loginUserId.includes(" ")) {
                    data = loginUserId.replace(/ /g, "+");
                  } else {
                    data = loginUserId;
                  }
                }
                let loginId = loginUserId ? securityFunctions.decryptText(data) : null;
                // set before jwt token so other api work proper
                sessionStorage.setItem('JwtToken', res.respObj.JwtToken);
                sessionStorage.setItem('RefreshToken', res.respObj.RefreshToken);
                sessionStorage.setItem('JwtTokenExpiry', res.respObj.JwtTokenExpiry);
                securityFunctions.setSessionStorage('LoginUserData', JSON.stringify(res.respObj.userLogin));
                let date = new Date(moment(res.respObj.userLogin.last_login).format("YYYY MM DD hh:mm:ss") + " UTC");
                let lastLogin = moment(date.toString()).format("hh:mm:ss, DD MMM YYYY");
                sessionStorage.setItem('lastLogin', lastLogin);
                sessionStorage.setItem('userName', res.respObj.userLogin.first_name);
                this.commonService.FetchExtranetVendorMaster(res.respObj.userLogin.extranet_vendor_id, false).subscribe(data => {
                  if (data) {
                    securityFunctions.setSessionStorage('VData', JSON.stringify(data.Result[0]));
                  }
                });
                this.router.navigate(['/'])
                this.commonService.StartTimer();
              } else {
                this.router.navigate(['/Auth/Login']);
              }
            },
            error: err => {
              this.router.navigate(['/Auth/Login']);
            }
          });
        } else {
          this.router.navigate(['/Auth/Login']);
        }
      }
    });

  }

  // GetUserdata(userid) {
  //   if (userid) {
  //     return this.http.get(environment.adminAPIUrl + "/UserAccount/GetUserDetail/" + userid)
  //   } else {
  //     return of('continue');
  //   }
  // }
  UserIpDetails;
  GetIpAddress() {
    this.http.get("https://pro.ip-api.com/json/?fields=query,countryCode,lat,lon,city,proxy&&key=JZDsrdeBzIM0yyN").subscribe(res => {
      if (res) {
        this.UserIpDetails = res;
        let obj = {
          city: res['city'],
          countryCode: res['countryCode'],
          lat: res['lat'],
          lon: res['lon'],
          proxy: res['proxy'],
          iP: res['query'],
        }
        sessionStorage.setItem('IP', JSON.stringify(obj));
      }
    })
  };
}