import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {Http} from '@angular/http';
import {Headers} from '@angular/http';
import {CookieService} from 'ngx-cookie-service';
import {User, UsersService} from '../resorcess/users.service';
import {RolesService} from '../resorcess/roles.service';
import {Router} from '@angular/router';
import {environment} from '../../../environments/environment';
import {Dialog} from '../base_components/dialog/dialog';
@Injectable()
export class AuthService {
  auth: AuthService;
  private _currentUser: User;
  private _auth_token: string;
  /**
   * وقتی برنامه رفرش میشه به صورت پیش فرض ture هست وقتی init اجرا میشه false میشه دیگه تا وثتی که رفرش نشه init بررسی نمیشه و لاگین باقی میمونه
   */
  needToRunInit = true;

  /**
   * @param {Http} http  baray darkhadt hay http estefade mishe
   * @param {CookieService} cookieService baray save kardan token
   * @param router
   * @param userService
   * @param roleService
   * @param dialog
   * @param toasterService
   */
  constructor(private http: Http,
              private cookieService: CookieService,
              private router: Router,
              private userService: UsersService,
              private roleService: RolesService,
              private dialog: Dialog,
  ) {
    this.roleService.register();
  }

  get auth_token(): string {
    return this.cookieService.get('token');
  }

  set auth_token(value: string) {
    this._auth_token = value;
  }

  get currentUser(): User {
    return this._currentUser;
  }

  set currentUser(value: User) {
    this._currentUser = value;
  }

  /**
   *
   * @param username email user hast
   * @param password
   * @param type requestType user hast mesl dr ya parastar
   * @param cloud_token
   * @param remember
   * @returns {Observable<boolean>}
   */

  loginWithPassword(mobile, password, remember, app_package_name, app_version, app_sdk): Observable<boolean> {
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http.post(environment.app_url + 'login',
      'mobile=' + (mobile) + '&password=' + (password) +
      +'&app_package_name=' + (app_package_name)
      + '&app_version=' + (app_version) + '&app_sdk=' + (app_sdk)
      ,
      {headers: headers})
      .map(res => res.json())
      .map(res => {
        if (res) {
          this.setLoginParams(res, remember, true);
        }
        return this.isLoggedIn();
      });
  }

  loginWithSmsToken(mobile, sms_token, remember, app_package_name, app_version, app_sdk): Observable<boolean> {
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http.post(environment.app_url + 'login',
      'mobile=' + (mobile) + '&sms_token=' + (sms_token) + '&app_package_name=' + (app_package_name)
      + '&app_version=' + (app_version) + '&app_sdk=' + (app_sdk)
      ,
      {headers: headers})
      .map(res => res.json())
      .map(res => {
        if (res) {
          this.setLoginParams(res, remember, true);
        }
        return this.isLoggedIn();
      });
  }


  /**
   * auth token
   */

  setToken(token: string, remember: boolean) {
    if (token === '') {
      this.cookieService.delete('token');
    } else {
      this.cookieService.set('token', token, remember ? 60 : 0);
    }
  }


  isLoggedIn(): boolean {
    return !!this.currentUser;
  }

  logout() {
    this.currentUser = null;
    this.setToken('', false);
    if (!this.isLoggedIn()) {
      this.router.navigateByUrl('/auth/passwordSignin');
    } else {
      // todo ino test kon
      this.router.navigateByUrl('');
      return false;
    }
  }

  convertUserFromText(userString: string): User {
    const userObj = this.userService.new();
    if (userString !== 'null') {
      this.userService.convert(JSON.parse(userString), userObj);
    }
    return userObj;
  }

  /**
   *
   * @returns {Observable<boolean>}
   */
  init(): Promise<boolean> {
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    headers.append('Accept', 'application/vnd.api+json');
    headers.append('Authorization', 'Bearer ' + this.auth_token);
    return this.http.post(environment.app_url + 'init',
      'app_package_name=' + 'hpen_web' +
      '&app_version=' + '1' +
      '&app_sdk=' + '1',
      {headers: headers})
      .toPromise()
      .then(response => {

        response = response.json();
        this.setLoginParams(response, null, false);
        if (this.isLoggedIn()) {
          return Promise.resolve(true);
        } else {
          return Promise.reject(false);
        }
      }).catch(reason => {
        console.log('reason is', reason);
        this.needToRunInit = false;
        return Promise.reject(false);
      });
  }

  // in tabe request id va status ro mifreste be server
  /***
   *
   * @param loginResponse رسپانس init  و login  هست
   * @param remember این واسه ی مرا بخاطر بسپار هست
   * @param fromLogin سرور در صورتی به ما توکن میده که لاگین کنیم  اینجا میگه  اگه لاگین  بود توکن ست کن
   */
  setLoginParams(loginResponse, remember?: boolean, fromLogin?: boolean) {
    this.needToRunInit = false;
    this.currentUser = this.convertUserFromText(loginResponse['user']);
    if (remember == null) {
      remember = false;
    }
    if (fromLogin) {
      this.setToken(loginResponse['token'], remember);
    }
    localStorage.setItem('basics', JSON.stringify(loginResponse['basics']));
    localStorage.setItem('columns', JSON.stringify(loginResponse['columns']));
  }

  mobileExists(mobile, type): Observable<any> {
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    headers.append('Accept', 'application/vnd.api+json');
    return this.http.post(environment.app_url + 'mobileExists',
      'mobile=' + (mobile) + '&type=' + (type), {headers: headers});
  }
}
