import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';

import {EnvProperties} from '../../openaireLibrary/utils/properties/env-properties';

import {Session, User} from '../../openaireLibrary/login/utils/helper.class';
import {LoginErrorCodes} from '../../openaireLibrary/login/utils/guardHelper.class';
import {CuratorService} from '../../openaireLibrary/connect/curators/curator.service';
import {Curator} from '../../openaireLibrary/utils/entities/CuratorInfo';
import {HelperFunctions} from '../../openaireLibrary/utils/HelperFunctions.class';
import {UtilitiesService} from '../../openaireLibrary/services/utilities.service';
import {HelpContentService} from '../../services/help-content.service';
import {AlertModal} from '../../openaireLibrary/utils/modal/alert';
import {UserManagementService} from '../../openaireLibrary/services/user-management.service';
import {Title} from '@angular/platform-browser';

@Component({
  selector: 'curator',
  templateUrl: './curator.component.html',
})

export class CuratorComponent implements OnInit {

  public showLoading = true;
  public updateErrorMessage = '';
  public successfulSaveMessage = '';

  public curatorsEnabled;
  public newCurator;

  public communityId = null;

  public affiliationsChanged = false;
  public hasChanged = false;
  public curatorId = null;
  public curator: Curator = null;
  public photo: any = null;
  public properties: EnvProperties = null;
  public user: User;

  private file: File = null;
  private maxsize: number = 200 * 1024;
  public enabled = true;
  private deletePhoto = false;

  @ViewChild('privacyStatement') privacyStatement: AlertModal;

  constructor(private element: ElementRef,
              private route: ActivatedRoute,
              private _router: Router,
              private title: Title,
              private curatorService: CuratorService,
              private utilitiesService: UtilitiesService,
              private helpContentService: HelpContentService,
              private userManagementService: UserManagementService) {
  }


  ngOnInit() {
    this.route.data.subscribe((data: { envSpecific: EnvProperties }) => {
      this.properties = data.envSpecific;
      if (!Session.isLoggedIn()) {
        this._router.navigate(['/user-info'], {
          queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}
        });
      } else {
        this.route.queryParams.subscribe((params) => {
          this.communityId = params['communityId'];
          this.title.setTitle('Administration Dashboard | Personal Info');
          this.showLoading = true;
          this.updateErrorMessage = '';
          this.userManagementService.getUserInfo().subscribe(user => {
            this.user = user;
            this.curatorId = this.user.id;
            this.curatorService.getCurator(this.properties, this.curatorId).subscribe(
              curator => {
                if (curator && Object.keys(curator).length > 0) {
                  this.curator = curator;
                  this.curator.email = this.user.email;
                  if (this.curator.photo && this.curator.photo !== '') {
                    this.photo = this.properties.utilsService + '/download/' + this.curator.photo;
                  } else {
                    this.photo = 'assets/common-assets/curator-default.png';
                  }
                  this.curatorsPageStatus();
                  this.showLoading = false;
                  HelperFunctions.scroll();
                } else {
                  this.newCurator = true;
                  this.curator = new Curator();
                  this.curator._id = this.curatorId;
                  this.curator.email = this.user.email;
                  this.curator.name = this.user.fullname;
                  this.curator.affiliations = [];
                  this.curator.bio = '';
                  this.curator.photo = null;
                  this.photo = 'assets/common-assets/curator-default.png';
                  this.showLoading = false;
                  HelperFunctions.scroll();
                }
              },
              error => {
              }
            );
          });
        });
      }
    });

  }

  public resetForm() {
    if (!Session.isLoggedIn()) {
      this._router.navigate(['/user-info'], {
        queryParams:
          {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}
      });
    } else {
      if (this.curatorId != null && this.curatorId !== '') {
        this.showLoading = true;
        this.updateErrorMessage = '';
        this.curatorService.getCurator(this.properties, this.curatorId).subscribe(
          curator => {
            if (curator) {
              this.curator = curator;
              this.curator.email = this.user.email;
              if (this.curator.photo && this.curator.photo !== '') {
                this.photo = this.properties.utilsService + '/download/' + this.curator.photo;
              } else {
                this.photo = 'assets/common-assets/curator-default.png';
              }
              this.showLoading = false;
              this.curatorsPageStatus();
              HelperFunctions.scroll();
            } else {
              this.newCurator = true;
              this.curator = new Curator();
              this.curator._id = this.curatorId;
              this.curator.email = this.user.email
              this.curator.name = this.user.fullname;
              this.curator.affiliations = [];
              this.curator.bio = '';
              this.curator.photo = null;
              this.photo = 'assets/common-assets/curator-default.png';
              this.showLoading = false;
              HelperFunctions.scroll();
            }
          },
          error => {
          }
        );
      }
      this.resetChange();
    }
  }

  private curatorsPageStatus() {
    this.helpContentService.getCommunityFull(this.communityId, this.properties.adminToolsAPIURL).subscribe((community) => {
      for (let page of community.pages) {
        if (page['route'] === '/curators') {
          this.curatorsEnabled = page['isEnabled'];
          return;
        }
      }
      this.curatorsEnabled = false;
      console.log(this.curatorsEnabled);
    });
  }

  private change() {
    this.hasChanged = true;
    this.affiliationsChanged = true;
  }

  private resetChange() {
    this.hasChanged = false;
    this.affiliationsChanged = false;
  }

  public resetMessages() {
    this.successfulSaveMessage = '';
    this.updateErrorMessage = '';
  }

  handleUpdateError(message: string, error) {
    this.resetMessages();
    this.updateErrorMessage = message;
    console.log('Server responded: ' + error);

    this.showLoading = false;
  }

  handleSuccessfulSave(message) {
    this.resetMessages();
    this.showLoading = false;
    HelperFunctions.scroll();
    this.successfulSaveMessage = message;
  }

  fileChangeEvent(event) {
    this.showLoading = true;
    if (event.target.files && event.target.files[0]) {
      this.file = event.target.files[0];
      if (this.file.type !== 'image/png' && this.file.type !== 'image/jpeg') {
        this.handleUpdateError('You must choose a file with type: image/png or image/jpeg!', null);
        this.file = null;
      } else if (this.file.size > this.maxsize) {
        this.handleUpdateError('File exceeds size\'s limit! Maximum resolution is 256x256 pixels.', null);
        this.file = null;
      } else {
        this.updateErrorMessage = '';
        const reader = new FileReader();
        reader.readAsDataURL(this.file);
        reader.onload = () => {
          this.photo = reader.result;
          this.showLoading = false;
          HelperFunctions.scroll();
        };
      }
    }
  }


  updateCurator() {
    if (!Session.isLoggedIn()) {
      this._router.navigate(['/user-info'], {
        queryParams:
          {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}
      });
    } else {
      if ((this.hasChanged || this.affiliationsChanged) && this.curator && this.curator.name && this.curator.name !== '') {
        this.showLoading = true;
        if (this.file) {
          this.utilitiesService.uploadPhoto(this.properties.utilsService + '/upload/' + this.curator._id, this.file).subscribe((res) => {
              if (this.curator.photo && this.curator.photo !== '') {
                this.utilitiesService.deletePhoto(this.properties.utilsService + '/delete/' + this.curator.photo).subscribe();
              }
              this.curator.photo = res.filename;
              this.curatorService.updateCurator(this.properties, this.curator).subscribe((curator) => {
                  if (curator) {
                    this.handleSuccessfulSave('Your data has been saved successfully!');
                    this.newCurator = false;
                    this.resetChange();
                  }
                },
                error => {
                  this.handleUpdateError('An error has occurred. Try again later!', error);
                  this.resetChange();
                });
            }, error => {
              this.handleUpdateError('An error has occurred during photo uploading.', error);
            }
          );
        } else {
          if (this.deletePhoto) {
            this.utilitiesService.deletePhoto(this.properties.utilsService + '/delete/' + this.curator.photo).subscribe();
            this.curator.photo = '';
          }
          this.curatorService.updateCurator(this.properties, this.curator).subscribe((curator) => {
              if (curator) {
                this.handleSuccessfulSave('Your data has been saved successfully!');
                this.resetChange();
              }
            },
            error => {
              this.handleUpdateError('An error has occurred. Try again later!', error);
              this.resetChange();
            });
        }
      }
    }
  }

  onNameChange() {
    this.hasChanged = true;
    if (!this.curator.name || this.curator.name === '') {
      this.enabled = false;
    } else {
      this.enabled = true;
    }
  }

  removePhoto() {
    this.deletePhoto = true;
    this.hasChanged = true;
    this.photo = 'assets/common-assets/curator-default.png';
  }

  privacy() {
    this.privacyStatement.cancelButton = false;
    this.privacyStatement.okButtonText = 'Close';
    this.privacyStatement.alertTitle = 'Privacy policy statement';
    this.privacyStatement.open();
  }
}
